2
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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Matt
  • 484
  • 5
  • 15

3 Answers3

3

You have used name=z.nextLine(), hence such behavior, Replace it with name=z.next(). Below is the edited code:

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.next();
System.out.println("your name is :"+name);

System.out.println("Give the grade:\n");
grade=z.nextFloat();
newuser
  • 8,338
  • 2
  • 25
  • 33
Jhanvi
  • 5,069
  • 8
  • 32
  • 41
2

When you read int value using nextInt, it reads only the int value, it skips the new line character. The latter will be read in the next nextLine causing it to skip the "real" input.

You can fix this by adding another nextLine before the "real" nextLine, it'll swallow the '\n' that you don't want to read.

Important note: Don't use int to store ID value! Use String instead!

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

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:");
newuser
  • 8,338
  • 2
  • 25
  • 33