I am a beginner in Java Programming. I am not able to figure out exactly where I am going wrong. I am trying to print out a string, which is to be taken by the user.
But my Program just prints the very first line of the code and exits without even asking for the second input.
Here is the code.
package com.company;
import java.util.Scanner;
public class string {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "XYZ";
int age = sc.nextInt();
String sem = sc.nextLine();
System.out.format("The name of the guy is %s and his age is %d \n",name , age );
System.out.printf("His ongoing semester is %s",sem);
}
}
Here is my program, code asks for the input of age, and without further asking for the input of other strings it exits.
>Solution :
package com.company;
import java.util.Scanner;
public class string {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "XYZ";
int age = sc.nextInt(); sc.nextLine();
String sem = sc.nextLine();
System.out.format("The name of the guy is %s and his age is %d \n",name , age );
System.out.printf("His ongoing semester is %s",sem);
}
}
I dont exactly know but I mostly face this issue and int age = sc.nextInt(); sc.nextLine(); this kind of fix to solve this issue. You can also use sc.next() if you want to take only one word from user