Search code examples
javaprintwriter

First iteration of for loop automatically proceeding with scanner input


I have a class that takes input from the Scanner class and outputs via the PrintWriter class. When the program hits the for loop it automatically runs the first iteration without waiting to get input from the user.

It should read Insert item 1:

However it reads Insert Item 1 Insert Item 2.

After the first iteration everything runs fine.

Any help in regards to why this is happening would be greatly appreciated.

InputSplicer(Scanner input)
{
    this.input = input;
    array = new ArrayList<String>();
}

void splice()
{
    System.out.println("What is the output file destination?");
    outputFile = input.next();
    outputFileFile = new File(outputFile);
    try {
        output = new PrintWriter(outputFileFile);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("How many items are in the query?");
    lengthOf = input.nextInt();

    for(int i = 1; i <= lengthOf; i++)
    {   
        System.out.println("Insert item " + i);
        //spaces in output are not working for example item 1 cannot equal jason tavano can equal jasontavano

        s = input.nextLine();

        s.trim();

        if(s.equalsIgnoreCase("null"))
        {
            s = "";

        }
        if(i != lengthOf)
            array.add(s + pipe);
        else
            array.add(s);
    }   
    for(int i = 0; i < array.size(); i++)
        output.print(array.get(i));
    output.close(); 
}
}

Solution

  • problem:

    s = input.nextLine();
    

    When you input the number from the nextInt it will consume the newLine character from it thus iterating to the second loop in your for loop

    solution:

    consume the newLine character first before going to the loop

    sample:

    System.out.println("How many items are in the query?");
    lengthOf = input.nextInt();
    input.nextLine(); //will consume the newLine character from the input lengthOf