0

I called a scanned object, using same object I am trying to take from user a int and a string.

Scanner scan = new Scanner(System.in);
//for a int 
int first_value  = scan.nextInt();
System.out.println(first_value); 
//for a string
String  first_name = scan.nextLine();
System.out.println(first_name); 

Here console not waiting for string but If I use another object then it's working fine.

 Scanner insert = new Scanner(System.in);
 String name = insert.nextLine();

Is it possible to get int and string using same Scanner object ?

Satu Sultana
  • 507
  • 7
  • 19

2 Answers2

3

That is because after reading int there left a new line character which was consumed by your scan.nextLine and it did not wait for your next input. You need to consume it before reading a String.

Scanner scan = new Scanner(System.in);
//for a int 
int first_value  = scan.nextInt();
scan.nextLine();
System.out.println(first_value); 
//for a string
String  first_name = scan.nextLine();
System.out.println(first_name)
Sanjeev
  • 9,741
  • 2
  • 19
  • 33
  • Because the new line character is buffered in `Scanner` not in `System.in`so if you try reading it with a different scanner it will wait for your input. – Sanjeev Jun 21 '16 at 06:22
0

Use System.out.println("Enter Your Age"); and System.out.println("Enter Your Name"); just before taking input from user by Scanner Object.

System.out.println("Enter your first name:");
String first_name = scan.nextLine();

System.out.println("Enter your age:");
int age = Integer.parseInt(scan.nextLine());

Now it enables you to hold the screen For entering you Input to the Program.

Vikrant Kashyap
  • 5,028
  • 1
  • 23
  • 46