Java.util.Scanner,关闭问题

时间:2014-07-20 08:26:44

标签: java java.util.scanner

好的,所以这段代码的问题在于,如果它不止一次遍历循环,关闭扫描程序会导致代码忽略扫描进一步的用户输入。我知道问题必须是Scanner类中的内部问题,但是有没有人能够以更安全的方式关闭扫描仪? (如果您没有意识到我正在遇到的问题,可能有助于复制代码并尝试输入“55”或“j”)。

public static void main(String[] args){
    int numCom = 0, count = 0;
    boolean valid = false;

    do{
        Scanner num = new Scanner(System.in);
        try{
            if(count == 0){
                System.out.println("Okay, how many adversaries would you like to be put up against? (between 1-8)");
                count++;
            }else{
                System.out.println("Error!\nPlease enter a number between 1-8.");
            }
            numCom = num.nextInt();
        }catch(Exception e){}
        if(numCom < 9 && numCom > 0){
            valid = true;
        }
        num.close();
    }while(!valid);
}//main()

5 个答案:

答案 0 :(得分:1)

您需要确保只关闭扫描仪,而不是System.in。在这种情况下,调用scanner.close()依次调用您在构造函数(System.in)中提供的源。你有两个选择。将要使用的更优雅 http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/input/CloseShieldInputStream.html

Scanner num = new Scanner(new CloseShieldInputStream(System.in));

纯java解决方案

public class Scan {
private static final class MyShieldedSystemIn extends InputStream {
    @Override
    public int read(byte[] b) throws IOException {
        return System.in.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return System.in.read(b, off, len);
    }

    @Override
    public void close() throws IOException {
        // do nothing
        System.out.println("ignoring call to close()");
    }

    @Override
    public int read() throws IOException {
        return System.in.read();
    }
}
final static InputStream SSI = new MyShieldedSystemIn();
public static void main(String[] args){
    int numCom = 0, count = 0;
    boolean valid = false;


    do{
        Scanner num = new Scanner(SSI);
        try{
            if(count == 0){
                System.out.println("Okay, how many adversaries would you like to be put up against? (between 1-8)");
                count++;
            }else{
                System.out.println("Error!\nPlease enter a number between 1-8.");
            }
            numCom = num.nextInt();
        }catch(Exception e){}
        if(numCom < 9 && numCom > 0){
            valid = true;
        }
        num.close();
    }while(!valid);
}//main()

}

答案 1 :(得分:0)

在循环外创建并关闭扫描仪。像这样:

public static void main(String[] args) {
        int numCom = 0, count = 0;
        boolean valid = false;
        Scanner num = new Scanner(System.in);

        do {
            try {
                if (count == 0) {
                    System.out.println("Okay, how many adversaries would you like to be put up against? (between 1-8)");
                    count++;
                } else {
                    System.out.println("Error!\nPlease enter a number between 1-8.");
                }
                numCom = num.nextInt();
            } catch (Exception e) {}
            if (numCom < 9 && numCom > 0) {
                valid = true;
            }
        } while (!valid);
        num.close();
    } //main()

答案 2 :(得分:0)

尝试:java 7+ http://ideone.com/dxtXmz

 public static void main(String[] args){
    int numCom = 0, count = 0;
    boolean valid = false;
        try (Scanner num = new Scanner(System.in)) {
            do{
                try{
                    if(count == 0){
                        System.out.println("Okay, how many adversaries would you like to be put up against? (between 1-8)");
                        count++;
                    }else{
                        System.out.println("Error!\nPlease enter a number between 1-8.");
                    }
                    numCom = num.nextInt();
                }catch(Exception e){}
                if(numCom < 9 && numCom > 0){
                    valid = true;
                }
            }while(!valid);
        }
}//main()

尝试:http://ideone.com/LaN6kF

public static void main(String[] args){
int numCom = 0, count = 0;
boolean valid = false;

    Scanner num = new Scanner(System.in);
do{
    try{
        if(count == 0){
            System.out.println("Okay, how many adversaries would you like to be put up against? (between 1-8)");
            count++;
        }else{
            System.out.println("Error!\nPlease enter a number between 1-8.");
        }
        numCom = num.nextInt();
    }catch(Exception e){}
    if(numCom < 9 && numCom > 0){
        valid = true;
    }
}while(!valid);

    num.close();
}//main()

基本上资源:scanner:只分配一次并重复使用。 当不需要时,它关闭。

答案 3 :(得分:0)

如果您还需要处理字符串,请尝试以下方法: http://ideone.com/f7IMwD

public static void main(String[] args) {
        int numCom = 0, count = 0;
        boolean valid = false;
        try (Scanner num = new Scanner(System.in)) {
            do {
                try {
                    if (count == 0) {
                        System.out.println("Okay, how many adversaries would you like to be put up against? (between 1-8)");
                        count++;
                    } else {
                        System.out.println("Error!\nPlease enter a number between 1-8.");
                    }
                    String line = num.nextLine();
                    numCom = Integer.parseInt(line);
                    if (numCom < 9 && numCom > 0) {
                        valid = true;
                    }
                } catch (NumberFormatException e) {
                    valid = false;
                }

            } while (!valid);
        }
    }//main()

答案 4 :(得分:0)

关闭Scanner时,它会关闭其输入源,在本例中为System.in。关闭System.in后,您将无法再阅读输入内容。不要关闭Scanner。它没有任何需要关闭的资源,除非你想要关闭输入源,在这种情况下你不需要。如果您删除num.close();电话,您的代码将正常运行。

编辑:不过,你正在做大量工作。您的代码长度可以减半而不会丢失功能:

int numAdversaries;
System.out.println("Okay, how many adversaries would you like to be put up against? (between 1-8)");
for (;;) {
    try {
        numAdversaries = new Scanner(System.in).nextInt();
        if (numAdversaries >= 1 && numAdversaries <= 8) break;
    } catch (Exception e) {}
    System.out.println("Error!\nPlease enter a number between 1-8.");
}