0
int i = 4;
String s ="Hi ";

Scanner scan = new Scanner(System.in);

System.out.println("enter Integer");
int m=scan.nextInt();

System.out.println("enter string");
*String t = scan.next();
**String t = scan.nextLine();

System.out.println(i+m);
System.out.println(s+t);

when I use *scan.next() then it will only read a single word, another side when I use **scan.nextLine() it will directly show the output

Ele
  • 31,191
  • 6
  • 31
  • 67

1 Answers1

0

Call nextLine() after nextint() to consume \n.

int a = scanner.nextInt()
scanner.nextLine() // to flush end of line
 ... // Then read string
String s = scanner.next()

The whole story

After Entering a number, Say 5.. the stream looks like

5\n

When nextInt() is called, the stream looks like

\n

After you enter string, say `hi

\nhi

After next() is called the stream looks like

hi

The cause of problem: next() consume till \n.
When it is called \n was first character in the stream. so it read empty string "".

The Mighty Programmer
  • 1,047
  • 10
  • 21