【问题标题】:Scanner JAVA certain requirements扫描仪 JAVA 某些要求
【发布时间】:2018-09-13 04:00:49
【问题描述】:

对于我的代码,我需要制作一个扫描仪,它可以为我的一个学校项目获取用户输入。但是,输入只能是 3 位数字,否则它应该提示用户再次要求输入?我怎么能用 JAVA 做到这一点?谢谢。

这是我目前拥有的,但它不起作用

    Scanner sc = new Scanner(System.in);

    while(sc.nextInt() > 99 && sc.nextInt() < 1000) {
        int n = sc.nextInt();
    }

我目前有这个,但它不起作用。

【问题讨论】:

  • 每次调用sc.nextInt() 时,它都会再次尝试从System.in 获取输入。将值分配给int 变量,然后测试该值是否有效

标签: java string int


【解决方案1】:

在您尝试将它分配给一个 int 变量之前,我会验证您在扫描仪中是否有一个 int。您可以使用 Scanner.hasNextInt() 方法做到这一点。

试试这样的方法,看看它是否适用于您的应用程序:

Scanner scanner = new Scanner(System.in);
        int input = 0;

        while(input < 100 || input > 999) {
            System.out.print("Please enter a 3-digit number:");
            if(scanner.hasNextInt()) {
                input = scanner.nextInt();
            }
            else {
                scanner.next();
            }
        }

【讨论】:

  • 永远记得关闭ScannerexceptSystem.in上关闭Scanner,以防需要使用System.in稍后再来。
  • 公平点,您需要确保在关闭 Scanner 之前完全完成。因此,如果您对这个程序有更多的了解,请将 scanner.close() 移至代码中的安全位置。
  • 或者干脆不要关闭Scanner。如果您只想在程序完成后关闭它,则无需关闭它,因为此时您不再关心内存泄漏。
  • 好收获!我已经更新了代码以反映正确的边界。
【解决方案2】:

Scanner.nextInt() 会提示你输入,所以你不应该在 while 条件下使用它。

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while(!(n > 99 && n < 1000)) {
    n = sc.nextInt();
}

【讨论】:

    【解决方案3】:

    这可能会有所帮助:

    public static void main(String[] args) throws Exception {
    
        int x;
    
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number greater than 99 and less than 1000: ");
        x = in.nextInt();
    
        while (x >= 1000 || x <= 99) {
            System.out.println("Invalid number: Enter in range");
            x = in.nextInt();
        }
    
        in.close();
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多