0

I am attempting to read each integer from an infile and passing that on to the method adScore which determines the letter grade, and total count of all the grades and the highest exam score and lowest exam score. But my while loop when doing the for loop isn't pulling in the data from the infile as I am debugging it after the for loop doing a system.out.print. And what returns are just the numbers 0-29 which is my counter in the loop. Can assist me as to what I am doing wrong so that I can pull in the grade scores from the infile?

Regards.

        while(infile.hasNextInt())
        {
            for(int i=0; i <30; i++)//<-- it keeps looping and not pulling the integers from the     file.
            {
                System.out.println(""+i);//<--- I placed this here to test what it     is pulling in and it is just counting
                //the numbers 0-29 and printing them out.  How do I get each data    from the infile to store
                exam.adScore(i);//determines the count of A, B, C, D, F grades, total   count, min and max
            }
        }
4

2 回答 2

2

It's printing 0 - 29 because that's what you are telling it to do:

System.out.println(""+i)

will print out i, which is simply the integer you are using as the loop counter. You are never actually retrieving the next value from the Scanner object. I'm guessing this is homework, so I won't give you any code, but I will say that you definitely need to be using the nextInt() method of Scanner to retrieve the values from the input file and use that value inside your for-loop.

于 2012-04-15T02:04:25.123 回答
1

Tron's right --- you haven't actually asked the scanner to read the next integer. Scanner.hasNextInt() simply tests to see if there's an integer to be read. You're just telling i to loop through the values 0-29. I think you mean to do something like this:

while(infile.hasNextInt())
{
    int i = infile.nextInt();
    exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max
}

If you're not sure that every line in the input is an integer, you could do something like this:

while(infile.hasNext()) { // see if there's data available
    if (infile.hasNextInt()) { // see if the next token is an int
        int i = infile.nextInt(); // if so, get the int
        exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max
    } else {
        infile.next(); // if not an int, read and ignore the next token
    }
}
于 2012-04-15T05:03:26.857 回答