0
Scanner sc4 = new Scanner(System.in);
System.out.println("\nEnter the ID of the student you want to update!: ");
int id = sc4.nextInt();
System.out.println("Print1!");
String name = sc4.nextLine();
System.out.println("Print2!");
String address = sc4.nextLine();
System.out.println("Enter the updated contact Number of the student: ");
String contact = sc4.nextLine();
System.out.println("Enter the updated CourseID of the student: ");
int courseId = sc4.nextInt();
studentService.updateStudentById(id, name, address, contact, courseId);
break;

This code prints "Enter the ID of.." once and after receiving input from me, it prints both Print1 and Print2. Why does this happen?

Using scanner before every print statement solves this problem but I want a good programming approach towards this.

2 Answers2

1

Use java.util.Scanner#next() if you want to add new value to the buffer.

If you intentionally used java.util.Scanner#nextLine() to display data from buffer, then you have to put something in buffer (some string).

https://www.tutorialspoint.com/java/util/scanner_nextline.htm

0

A more complete answer is detailed here but to give an overview, nextInt() only consumes the integer that you supply in the Console but leaves the newline character \n as it is. When the nextLine() is called after nextInt(), it consumes this \n character and moves ahead (basically reading empty string). This behaviour can be remedied multiple ways.

One way is by using nextLine() instead of nextInt() and then casting to int using the following code String s = sc.nextLine();

int id = Integer.valueOf(s);

Alternatively, you can add an extra sc.nextLine() after sc.nextInt() to consume the newline character and then continue with your code. An interesting fact is that if you give multiple calls to sc.nextInt() then you only need to give one sc.nextLine() call at the end to consume the last newline character. All the previous newlines have already been skipped over by system input!