Why can't read this code: Exception in thread "main" java.util.NoSuchElementException, at java.util.Scanner.throwFor(Unknown Source),

StackOverflow https://stackoverflow.com/questions/22714236

<

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 Main.main(Main.java:14)>>

I am trying to make a file reader , it should read from textfile a 9 digit and make a ISBN Number. this gives constantly error : Exception in the thread....

the 9 digits are like this : 013601267< enter>

013031997

013292373 here is my code:

    File  fr = new File("ISBN.txt");
    Scanner in = new Scanner(fr);
    int s ; int sum; int c10;
    while (in.hasNextInt()) {
        int c1 = in.nextInt();
        int c2 = in.nextInt();
        int c3 = in.nextInt();
        int c4 = in.nextInt();
        int c5 = in.nextInt();
        int c6 = in.nextInt();
        int c7 = in.nextInt();
        int c8 = in.nextInt();
        int c9 = in.nextInt();

        String set = in.next();

         sum = Integer.parseInt(set);

         c10 = (c1 * 1 + c2 * 2 + c3 * 3 + c4 * 4 + c5 * 5 + c6 * 6 + c7
                * 7 + c8 * 8 + c9 * 9) % 11;
         s = c1+c2+c3+c4+c5+c6+c7+c8+c9;

        System.out.print("" + s);

        if (c10 == 1) 
            {
            System.out.println(set);

            } 
        else if (c10 % 11 == 0) 
            {
            System.out.println(set + "X");
            }

    }

}

}

有帮助吗?

解决方案

If your input is 013601267< enter>, in.nextInt() will take 013601267 as a single int because there are no space between digits. So you should call in.nextInt() one time and parse it into digits as you wanted.

Consider your input number begins with 0, you'd better use in.nextLine() to get it as a String instead of int, or the 0 at first position will be ignored.

You can do it like this:

while(in.hasNextLine) {
    String line = in.nextLine();
    int c1 = Integer.valueOf(line.substring(0,1));
    int c2 = Integer.valueOf(line.substring(1,2));
    //more lines here

}

其他提示

Well... Without seeing the stacktrace, that:

while (in.hasNextInt()) {
    int c1 = in.nextInt();
    int c2 = in.nextInt();
    int c3 = in.nextInt();
    int c4 = in.nextInt();
    int c5 = in.nextInt();
    int c6 = in.nextInt();
    int c7 = in.nextInt();
    int c8 = in.nextInt();
    int c9 = in.nextInt();

Is calling for that kind of exception. You have just checked one time if "in" hasNextInt, but you have called nextInt 9 times.

I think you are expecting that when your routine runs that in.nextInt() will see a number like this:

013601267

and return 0 the first time it is called, 1 the second time, 3 the third time, etc.

When, in fact, the first time you call in.nextInt() it is actually returning the entire number 013601267.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top