简体   繁体   中英

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

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. If you want to accept strings, just use 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). 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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