简体   繁体   中英

.noSuchElementException when asking the user for input

I can't run the following piece of code. I would like to know why I keep getting the .noSuchElementException error. I've seen in another post is due to the fact I'm using the same Input stream for both inputs, but creating a new Scanner or using the .close method doesn't seem to fix my problem.


class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner (System.in);

        int tooBig = 0; // parts too big
        int tooSmall = 0; // parts too small
        int perfectParts= 0; // perfect parts

        int a = scanner.nextInt();

        scanner.close();
        for (int i = 0; i <= a ; i++) {
            int j = scanner.nextInt();

            if(j == 1) {
                tooBig++;
            } else if (j == -1) {
                tooSmall++;
            } else if (j == 0) {
                perfectParts++;
            }
            scanner.close();
        }

        System.out.println(perfectParts + " " + tooBig
                + " " + tooSmall);



    }
}

Edit after having removed the scanner.close() method. I still get the same error:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner (System.in);

        int tooBig = 0; // parts too big
        int tooSmall = 0; // parts too small
        int perfectParts= 0; // perfect parts

        int a = scanner.nextInt();


        for (int i = 0; i <= a ; i++) {
            int j = scanner.nextInt();

            if(j == 1) {
                tooBig++;
            } else if (j == -1) {
                tooSmall++;
            } else if (j == 0) {
                perfectParts++;
            }

        }


        System.out.println(perfectParts + " " + tooBig
                + " " + tooSmall);



    }
}
class Main {
public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int tooBig = 0; // parts too big
    int tooSmall = 0; // parts too small
    int perfectParts= 0; // perfect parts

    int a = scanner.nextInt();

    
    for (int i = 0; i <= a ; i++) {
        int j = scanner.nextInt();

        if(j == 1) {
            tooBig++;
        } else if (j == -1) {
            tooSmall++;
        } else if (j == 0) {
            perfectParts++;
        }
        
    }

    System.out.println(perfectParts + " " + tooBig
            + " " + tooSmall);

    scanner.close();

}
}

scanner.close(); Should only be called at the very end. It's also not even necessary in your specific case and likely the reason why you're getting that exception.

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