简体   繁体   中英

For loop and while loop skipping Scanner

Here is my code:

    for (i = 0; i < numpc; i++){
        System.out.println(i);

        pcdata[i] = nameinput.next(); //get unsorted data

    }

I also tried using a while loop reiteration of the for loop. The program is meant to input multiple strings (the number of strings needed is denoted by numpc). The input/output is as follows:

0            // variable (i) counter
Apple 1 2 3  //Input
1
2
3
4

As you can see, the for loop runs 4 more times after the scanner receives a single input. This should not be happening unless i am missing something obvious?

When we are done with giving an input, we are giving it as input then we type ENTER. But when next() is taking input it takes everything before you pressed ENTER and then the next one takes only the ENTER. So this is how you are wasting an extra next()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM