简体   繁体   中英

Java Error “Exception in thread ”main“ java.util.NoSuchElementException”

I am getting this error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at IntegerSequence.main(IntegerSequence.java:73)

This is my first lab trying to read input from a text file and submit output to another text file. I need it to run 5 different 'for' loops. I thought I was close, and then I got the error. My code is as follows:

public static void main(final String[] args) throws IOException {

    File myFile = new File("input.txt");
    Scanner inputFile = new Scanner(myFile);
    PrintWriter outputFile = new PrintWriter("output.txt");

    // set accumulator
    int sum = 0;

    double iterations = inputFile.nextDouble();

    for (int start = 1; start <= iterations; start++) { 

        int starting = inputFile.nextInt();
        int ending = inputFile.nextInt();

        for (starting = 0 + starting; starting <= ending; starting++) {

            sum = sum + starting;
        }
    }
    outputFile.println(iterations); 
    outputFile.println(sum);


    outputFile.close();
    inputFile.close();
        }
}

Thank you for your help!

The input file is: 5 1 10 1 15

Your first number should be 2 then, since you only have two sets of starting and ending values. Or, you just need to provide three more pairs of values.

But, ideally you should program defensively with hasNextXYZ() checks for the kind of value you're about to read with a corresponding nextXYZ() read call or you run the risk of getting a NoSuchElementException .

Also, you're dealing exclusively with int s here. So, you should use int as the data type and call hasNextInt() and nextInt() only.

And since, starting = 0 + starting; seems to be doing nothing, the for loop can simply be

for (; starting <= ending; starting++) {
    sum += starting;
}

ie the initialization expression in a for loop is optional.


To calculate the sums separately instead of a cumulative total, you need to move the sum and it's associated println() calls to inside the loop.

int iterations = inputFile.nextInt();
outputFile.println(iterations); 

for (int start = 1; start <= iterations; start++) { 

    int starting = inputFile.nextInt();
    int ending = inputFile.nextInt();

    int sum = 0; // reset sum to 0

    for (; starting <= ending; starting++) {
        sum += starting;
    }
    outputFile.println(sum);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM