Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the prompt in my for loop printing twice the first time?

The first print statement in my for loop is printed twice before moving on to the next line. But then it runs through the loop like it should after that?

I tried using my debugger, but I've never used it before, we haven't gone over using it in any of my classes and I wasn't too 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);

    }

}  
like image 282
twjohns29 Avatar asked Oct 02 '14 03:10

twjohns29


1 Answers

You have what's called an off-by-one error. One of the fundamentals of many languages is that they are zero-based when it comes to indexing. You have got that half-right, you have one bug (actually two), and instead of fixing that bug, you have only fixed the symptom....

Off by one bug

The bug is in your for-loop:

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

Where you are looping one time too many... you should use < instead of <= in the test condition. That way you will loop numElements times.

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

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

to be:

ArrayBndQueue queue = new ArrayBndQueue<>(numElements);

That should sort out the extra loop, and you will still have space for the values.

Scanner management bug

Scanner.nextInt() only pulls the int value off the scanner, not the terminating newline/carriage-return, so when you call nextLine() in your loop it clears the already-in-the-scanner line, instead of waiting for input.

You need to clear the line from the scanner before advancing after the nextInt() call:

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

That should clear your scanner for the next input.

From the documentation:

nextInt() - Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

"advances past the input that matched" means before the newline/carriage-return.

like image 72
rolfl Avatar answered Sep 21 '22 17:09

rolfl