Saturday 25 June 2016

java - Skip over inputing string




int id;

float grade;
String name;
Scanner z= new Scanner(System.in);
System.out.println("Give the id:\n");
id=z.nextInt();
System.out.println("your id is :"+id+"\n");

System.out.println("Give the name:");
name=z.nextLine();
System.out.println("your name is :"+name);


System.out.println("Give the grade:\n");
grade=z.nextFloat();


The problem goes like this.It inputs the integer but when it comes to the String, it prints "Give the name" but it doesn't waits until I type something, it skips to the next instruction.



Why's that?


Answer



The problem is with the input.nextInt() command it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine()




id  = z.nextInt();
System.out.println ("your id is :"+id+"\n");
z.nextLine ();// add this line between the next line read

System.out.println("Give the name:");


or




id = Integer.parseInt(z.nextLine());
System.out.println ("your id is :"+id+"\n");
System.out.println("Give the name:");

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...