0

I want to break loop when I send nothing to input. But when I type something to input at nameS second time loop break by itself although the input wasn't empty.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(true) {
        System.out.print("Name: ");
        String nameS = sc.nextLine();
        if(nameS.isEmpty()) {
            break;
        }
        System.out.print("Student number: ");
        int numberS = sc.nextInt();
    } 
}
AbdelAziz AbdelLatef
  • 2,989
  • 6
  • 17
  • 38
  • Think about that `Enter` key you end your input as. That `Enter` key will be added as a newline in the input buffer. So what do you think happens when your `nextLine` call reads that newline? – Some programmer dude Oct 05 '19 at 19:26
  • As you can see I wasn't looking enough because I couldn't find a similar problem. My bad. – Kuba Kamiński Oct 06 '19 at 10:13

1 Answers1

0

nextInt() or next() method does not read enter. usually after number you must be pressing enter which is not readied by above method. a sort cut to avoid this is keep 1 extra sc.nextLine() method call. it will read and discard enter.

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.print("Name: ");
    String nameS = sc.nextLine();
    if (nameS.isEmpty()) {
        break;
    }
    System.out.print("Student number: ");
    int numberS = sc.nextInt();
    sc.nextLine();//you need to add this line in your code
    System.out.println(numberS);
}
AbdelAziz AbdelLatef
  • 2,989
  • 6
  • 17
  • 38
SSP
  • 2,703
  • 5
  • 27
  • 47