Why is the invitation in my print for the cycle twice for the first time?

The first print statement in a for for loop prints twice before moving on to the next line. But then he goes through the loop, as follows after that?

I tried using my debugger, but I never used it before, we did not use it in any of my classes, and I was not sure what I was doing

public static void main(String[] args) { int numElements; Scanner keyboard = new Scanner(System.in); System.out.println("How many people are you adding: "); numElements = keyboard.nextInt(); ArrayBndQueue queue = new ArrayBndQueue<>(numElements + 1); for(int index =0; index <= numElements; index++) { System.out.println("Enter a gender and name (ex: f jenny)"); String name = keyboard.nextLine(); System.out.println(name); queue.enqueue(name); } } 
+6
source share
2 answers

You have what is called an error at a time . One of the basics of many languages ​​is that they are zero-based when it comes to indexing. You have half the rights, you have one error (actually two), and instead of fixing this error, you only fixed a symptom ....

Disabled by one error

Error in your for-loop:

 for(int index =0; index <= numElements; index++) 

If you loop one time too much ... you should use < instead of <= in the test state. This way you will quote numElements times.

Instead of fixing it, you made the 1-element of the queue too large, so you should change:

 ArrayBndQueue queue = new ArrayBndQueue<>(numElements + 1); 

:

 ArrayBndQueue queue = new ArrayBndQueue<>(numElements); 

This should parse the extra loop, and you will still have room for the values.

Scanner control error

Scanner.nextInt() only pulls the int value from the scanner, and does not complete a new line / carriage return, so when you call nextLine() in its loop, it clears the line already in the scanner, instead of waiting for the input.

You need to clear the line from the scanner before proceeding after calling nextInt() :

 numElements = keyboard.nextInt(); keyboard.nextLine(); 

This should clear your scanner for next input.

From the documentation :

nextInt () - scans the next input token as int. This method will throw an InputMismatchException if the next token cannot be converted to a valid int value, as described below. If the transfer is successful, the scanner advances past the input.

"moves past the input that matches" means before returning a new line / carriage.

+13
source

The best solution is to simply remove elementType from the scanner method. By doing so, you do not allow the first instance of your loop to clear the input, as described above. The revised code is as follows:

 for(int index =0; index <= numElements; index++) { System.out.println("Enter a gender and name (ex: f jenny)"); //removed "Line" from ".nextLine" to prevent clearing below String name = keyboard.next(); System.out.println(name); queue.enqueue(name); } 
0
source

Source: https://habr.com/ru/post/976133/


All Articles