简体   繁体   English

Java Scanner输入仅接受数字

[英]Java Scanner input accepting only numbers

I'm trying to create this little program here, and I can't get this to work. 我正在尝试在这里创建这个小程序,但我无法使其正常工作。 I have 2 main doubles ( prvi and drugi ) and I want to make if the double converted to string (ether double prvi or drugi) contains any letters or symbols to print some text, if both doubles contain numbers, then I do my code there 我有2个主要的双打( prvidrugi ),我想确定如果将双打转换为字符串(以太坊prvi或drugi)包含任何字母或符号来打印一些文本,如果两个双打都包含数字,那么我在那做我的代码

Here's what I tried: 这是我尝试过的:

    Scanner sk = new Scanner(System.in);
        double prvi, drugi;

        System.out.println("Insert num: ");
        prvi = sk.nextDouble();

        System.out.println("Insert 2nd num: ");
        drugi = sk.nextDouble();

        String prviStr = String.valueOf(prvi);
        String drugiStr = String.valueOf(drugi);

        System.out.println("====================");

        if (prviStr.matches("[a-zA-Z]+") || drugiStr.matches("[a-zA-Z]+"))
            System.out.println("Only numbers!");

        else if (prviStr.matches("[0-9]+") && drugiStr.matches("[0-9]+")) {
            // I do my code here if both inputs are numbers 
         }

When you use nextDouble() , you are asking the scanner object to accept only valid Double inputs. 当使用nextDouble() ,您要求扫描程序对象仅接受有效的Double输入。 If you want to accept strings, just use next() . 如果要接受字符串,只需使用next() Change the lines as shown below. 如下所示更改行。

System.out.println("Insert num: ");
prvi = sk.next();

System.out.println("Insert 2nd num: ");
drugi = sk.next();

Surround your statement with try-catch and print an error if the sk returns an exception (in case you input something else then a double). 如果sk返回一个异常,则用try-catch括住语句,并输出一条错误消息(如果您输入其他内容,则输入double值)。 You no longer need to convert it to string or use regex this way. 您不再需要将其转换为字符串或使用正则表达式。

    Scanner sk = new Scanner(System.in);
    double prvi=0, drugi=0;

    try{
        System.out.println("Insert num: ");
        prvi = sk.nextDouble();

        System.out.println("Insert 2nd num: ");
        drugi = sk.nextDouble();
    }catch(Exception e){
        System.out.println("Only numbers!");
    }
    // Your code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM