Why doesn't this for-loop let me input text the first cycle?

前端 未结 2 970
旧时难觅i
旧时难觅i 2020-12-12 07:04

What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I r

相关标签:
2条回答
  • 2020-12-12 07:20

    Maybe you should change your loop to use 'sc.next()'

    for ( int x = 0; x < lines; x++ ) {
        System.out.print("String #" + x + ": ");
        text[x] = sc.next();
    }
    

    It can be explained by the Java API

    String next(): Finds and returns the next complete token from this scanner.

    String nextLine(): Advances this scanner past the current line and returns the input that was skipped.

    0 讨论(0)
  • 2020-12-12 07:39

    Buffering.

    nextInt() does not consume the newline in the input buffer that was put there when you entered the number of inputs. In the iteration 0 of the for loop, there's already a line of input in the buffer and nextLine() can complete immediately and the program will wait for new input line only in iteration 1. To ignore the newline in the input, you can add just another nextLine() call before entering the for loop.

    0 讨论(0)
提交回复
热议问题