Home > other >  How would I check If two user inputs only contains numbers(calculator program), I keep getting a run
How would I check If two user inputs only contains numbers(calculator program), I keep getting a run

Time:03-09

Hi I'm still new to java and I would like to know how to check if the user only input numbers and not letters my problem comes in when I had to parse the input from string to double to be able to add decimals together in the console. But when I googled to see how to check if my input is only numbers I had to take in a string input that gives me *2 inputs(hope I'm making sense).Is there maybe a easier version to do this or am I missing something.

public class javaCalculator {
    public static void main(String[] args){
        //initializing two scanners for numbers and operations and creating 3 variables
        Scanner numbers = new Scanner(System.in);
        Scanner operation = new Scanner(System.in);

        double number1;
        double number2;
        String operator;

        //getting user input for the type of operations and numbers they want to enter
        System.out.print("Enter the operator you would like to choose( , -, *, /): ");
        operator = operation.next();

        //My program didn't want to take decimals, so I had to parseDouble which takes the input as a string and then
        //converts(parse) it to a double which then makes my program run with decimal numbers
        System.out.print("Enter the first number: ");
        String num1 = numbers.nextLine();
        number1 = Double.parseDouble(numbers.nextLine());

        System.out.print("Enter your second number: ");
        String num2 = numbers.nextLine();
        number2 = Double.parseDouble(numbers.nextLine());

        boolean check1 = num1.matches("[0-9] ");
        boolean check2 = num2.matches("[0-9] ");

        if (check1 == true && check2 == true){
            System.out.println("...");
        }else {
            System.out.println("Only enter numbers not letters.");
        }

        //Using if else statements to check what operation was chosen above and then depending on
        //that choice( , -, *, /) printing a suitable answer to console
        //Creating a calculation variable to use in the writing to a file
        String calculation;
        if (operator.equals(" ")){
            calculation = (number1   "   "   number2   " = "   (number1   number2));
            System.out.println(calculation);

        }else if (operator.equals("-")){
            calculation = (number1   " - "   number2   " = "   (number1 - number2));
            System.out.println(calculation);

        }else if (operator.equals("*")){
            calculation = (number1   " * "   number2   " = "   (number1 * number2));
            System.out.println(calculation);

        }else if (operator.equals("/")){
            calculation = (number1   " / "   number2   " = "   (number1 / number2));
            System.out.println(calculation);

        }else{
            calculation = operator   ":"   " Is not a valid operator!";
            System.out.println(calculation);

        }

CodePudding user response:

Your code is trying to read the same number twice:

System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());

What you should do is read the number as a string, confirm that it is a number and then parse it only if it matches.

System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
boolean check1 = num1.matches("[0-9] ");
if(check1){
    number1 = Double.parseDouble(num1);
}
else{
    //Error handling
}

Alternatively you can simply try to parse the string directly and catch the exception i.e.

System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
try{
    number1 = Double.parseDouble(num1);
} catch(NumberFormatException e){
    //Error handling
}

CodePudding user response:

Your approach is OK. Although Scanner lib provides the nextDouble() method I recommend using the regular expression control you are using. Even though there are some little things to fix:

  1. You are parsing (convert from String to double) first, and then checking format. If for example, the user enters a letter your program will fail when parseDouble tries to convert the String to double. So, read the String from the input, apply the match control, and if there is no Error then parse.

  2. Your regular expression is matching any String that has 1 or more numbers. For example, the input Hello1 will match because there is at least one number. Then the parse will fail because Hello1 is not a valid number. You have to use a regular expression that matches only numbers. This expression will look like this: "^[0-9] $"

The ^ character means that the expression must match at the beginning of the line, and the $ character force that the expression match at the end of the line. In other words, this expression should have numbers from the beginning to the end of the string. It would be a good thing to add a .trim() (num1.trim().matches("[0-9] ");) to delete any extra white space at the beginning or at the end.

  1. The third recommendation is that if you don't want to use decimals may be Double type is not the proper data type to use. Double can represent decimals. The proper type should be Integers.

    number1 = Integer.parseInt(num1);

  2. @christopher When you raise error you are printing a message but the program keeps running. That's why you get the Error commented on @Turamarth solution comment

  • Related