1

Would anyone point me in the right direction, of why when i use a for loop the println function comes up two times in the output. Thanks

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the number of employees to calculate:");
    int numberEmployees = scan.nextInt();

    for(int i=0; i<numberEmployees; i++){               
            System.out.println("Enter First Name:");
            name = scan.nextLine();
            System.out.println("Enter Last Name:");
            last = scan.nextLine();
            System.out.println("Enter Document #:");
            document = scan.nextInt();
            System.out.println("Enter Basic Salary");
            basicSalary = scan.nextInt();
            System.out.println("Enter # of Hours");
            hours = scan.nextInt();
    }
}

OUTPUT

Enter the number of employees to calculate:
1
Enter First Name:
Enter Last Name:
daniel
Enter Document #:
4

2 に答える 2

3

The problem is that when you entered 1 with a new line, the nextInt() function doesn't remove the newline that you had from entering in the 1. Change your calls to scan.nextInt() to Integer.parseInt(scan.nextLine()) and it should behave the way you want.

To further explain; here's stuff from the Java API.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

and

The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input.

So, what evidently happens (I didn't see anything on the page to confirm it) is that after next(), hasNext(), and their related methods read in a token, they immediately return it without gobbling up delimiters (in our case, whitespace) after it. Thus, after it read in your 1, the newline was still there, and so the following call to nextLine() had a newline to gobble and did so.

于 2012-07-31T22:42:50.197 に答える
0

It appears that the newline character remains in your input after the first entry. When the next input is requested, the Scanner sees a newline character and interprets it as the end of the input. This makes it appear to skip every other input request. I would suggest checking out the Java API docs as to the exact behavior of Scanner's methods.

于 2012-07-31T22:42:09.633 に答える