【问题标题】:Java scanner adding variable conditionsJava扫描仪添加变量条件
【发布时间】:2015-08-22 01:53:54
【问题描述】:

我想问一下,如果我的用户输入一个字符或一个字符串,如果我想让他输入一个整数,我该如何准确地确定我的程序会做什么?我尝试按照我在引号中显示的方式进行操作,并尝试使用“等于”。第二种方法不起作用,第一种方法似乎表现得很奇怪,IF 部分有效,但 ELSE 完全被忽略了。

  public static void main(String[] args){

Scanner input=new Scanner(System.in);
System.out.print("Enter first integer: ");

int number1 = input.nextInt();// prompt
    if (number1 == (char)number1){

    System.out.println("Ok.");
    }
    else{  
     System.out.println("You were supposed to type in an int..");
     System.exit(1);
    }

System.out.print("Enter second integer: ");
int number2 = input.nextInt();// prompt
int sum =(number1 + number2);

System.out.printf("Your sum is: %d%n", sum);

  } 

【问题讨论】:

    标签: java java.util.scanner conditional-statements


    【解决方案1】:

    我建议你在hasNext()函数中使用正则表达式来进行更精细的控制,例如如果你寻找数字,请使用以下模式,

    sc.hasNext("[0-9]+")
    

    这里是 hasNext(String pattern) 函数的文档,

    public boolean hasNext(模式模式)

    如果下一个完整的标记与指定的模式匹配,则返回 true。完整的标记由匹配分隔符模式的输入添加前缀和后缀。此方法可能会在等待输入时阻塞。扫描仪不会超过任何输入。

    这是执行检查的简单代码,

    Scanner sc=new Scanner(System.in);
    int input = 0;
    while(true) {
        System.out.println("enter a number");
        if(sc.hasNext("[0-9]+")) {
            input = sc.nextInt();
            break;
        } else {
            System.out.println("not a number, try again");
            sc.next(); // just consume, but ignore as its not a number
        }
    }
    System.out.println("Entered number is : "+input);
    

    【讨论】:

    • 你能试试这个解决方案并告诉我吗?
    • 我刚试过,但是当我启动程序并输入一个 int 程序时,它只是跳到下一行,似乎停止工作,如果我输入一个字符或除数字以外的任何内容,它会抛出相同的错误和以前一样。
    • 有效吗?可以试试更新的吗?如果输入的值格式不正确,它会返回并要求输入。
    • 在旁注中,我可以在这种方法中以某种方式将数字设置得更高吗?除了 0-9 吗?
    • 是的,使用以下输入任意数字 sc.hasNext("[0-9]+") .. 我也在编辑结果。但是,如果您想对数字等进行更好的控制,请参阅此链接 - regular-expressions.info/numericranges.html
    【解决方案2】:

    您可以使用如下所示的用户定义函数并调用它

    public static boolean isNum(String input)  
    {  
      try  
      {  
        int d = Integer.parseInt(input);  
      }  
      catch(NumberFormatException e)  
      {  
        return false;  
      }  
      return true;  
    }
    

    然后你可以从你的主函数中调用这个方法。

    if(isNum(number1))
    

    【讨论】:

    • 非常不正确的答案...Scanner.nextInt() 将始终返回 int 或程序将停止。为什么建议进行额外验证。
    【解决方案3】:

    我不确定我是否理解您的问题,但我认为如下:

    用户总是会从输入中键入一个字符序列,那么你的程序必须检查该字符串是否可以转换为 Int,如果它不能转换它应该提示用户告诉输入的数据不是一个诠释。在这种情况下,您的 nextInt 将抛出 InputMismatchException。

    可能更优雅的解决方案是使用 hasNextInt(10): 公共静态无效主要(字符串[]参数){ 扫描仪输入=新扫描仪(System.in); System.out.print("输入第一个整​​数:");

        if (input.hasNextInt(10)){
            System.out.println("Ok. Typed number: " + input.nextInt());
        }else{  
            System.out.println("You were supposed to type in an int..");
            System.exit(1);
        }
    [...]
    }  
    

    【讨论】:

    • 这似乎也不起作用 - 我想要的是:我希望用户输入一个整数;如果用户输入除整数以外的任何内容,我想显示一条错误消息并可能向后移动一步,以便他可以再次输入,直到他写一个 int。
    • @bohdan 请看下面我的回答,
    【解决方案4】:

    试试这个,

            try {
                int number1 = sc.nextInt();// prompt
                System.out.println("Ok.");
            } catch (InputMismatchException ex) {
                System.out.println("You were supposed to type in an int..");
                System.exit(1);
            }
    

    【讨论】:

    • 我试过了,但它说:“变量号 1 未使用”,它也没有总结
    【解决方案5】:

    Scanner.nextInt();将输入的下一个标记扫描为 int。 如果输入不是 int,程序将不会执行超出此行。

    所以它永远不会进入 else 部分。不要进行任何 int 验证。

    我建议始终使用 try/catch 块来处理不正确的输入并显示有用的消息。也不要忘记关闭 Scanner 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 2012-01-03
      相关资源
      最近更新 更多