1

所以这是我的防崩溃扫描程序类的代码:

import java.util.*;
public class BPScanner {
    Scanner kb = new Scanner(System.in);
    public int nextInt() {
        while (true) {
            try {
                String input = kb.nextLine();
                int i = Integer.parseInt(input);
                return i;
        }
            catch (NumberFormatException e1) {}
            catch (NoSuchElementException e2) {}
            System.out.print("\nPlease input an integer: ");
            kb.close();
            kb = new Scanner(System.in);
        }
    }    
}

我从另一个类调用这个类:

public void scnr() {
    while (true){
        System.out.print("Type a num (for test), (0 to break)");
        int n = bpkb.nextInt();
        if (n == 0) break;
        System.out.println(n);
    }
}

当我运行它时,它会返回一个无限循环,不断说:

Please input an integer: 
Please input an integer: 
Please input an integer: 
Please input an integer: 

任何想法如何解决它?非常感谢您提前。

4

1 回答 1

1

nextInt只需从函数中删除以下代码:

kb.close();
kb = new Scanner(System.in);
于 2012-12-08T03:02:05.987 回答