0

I added a if statement that parses a entered number into a double to use when I do my calculations in the second if statement block, the program has to run if only numbers where entered and not letters, the program doesn't seem to read the numbers when I entered a double(5.5) but works fine when I enter a int(5) number/numbers.

Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);

double number1 = 0;
double number2 = 0;
String operator;


System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();


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


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


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


if (check1 == true && check2 == true){
    number1 = Double.parseDouble(num1);
    number2 = Double.parseDouble(num2);
}else {
    System.out.println("Only enter numbers not letters.");
}


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);

}

I think its maybe the ( . ) thats the problem, my output to console

Enter the operator you would like to choose(+, -, *, /): +
Enter the first number: 5.5
Enter your second number: 5.5
Only enter numbers not letters.
0.0 + 0.0 = 0.0 

And now the int numbers that works fine.

Enter the operator you would like to choose(+, -, *, /): +
Enter the first number: 5
Enter your second number: 5
5.0 + 5.0 = 10.0
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 2
    `^[0-9]+$` doesn't match a number with a dot in it, so yeah, that's the problem. – Federico klez Culloca Mar 15 '22 at 16:22
  • Does this answer your question? [Regular expression for floating point numbers](https://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers) – Federico klez Culloca Mar 15 '22 at 16:27
  • The regex match is not required, since parseToDouble throws an NumberFormatException as indicated by @jhamon link. In case of invalid string you should not only print a message but also stop further computation. – tangoal Mar 15 '22 at 16:30

2 Answers2

1

Do not use more than one Scanner object. There is no need for more than one, and this could also have some side effects you don't want to deal with.

Since you are using regular expression and others have suggested other solutions, I decided to show you how to use regular expression to evaluate a floating-point value. The correct expression for this is

[-+]?[0-9]*\\.?[0-9]+

or better yet...

[-+]?\\d*\\.?\\d+

This expression evaluates a value that may contain an optional sign (positive or negative) followed by zero or more digits, then followed by optional decimal point and an unlimited number of decimal digits. However, if the decimal point is used, at least one digit must be present. In a case like +2., only the +2 is matched.

The code below is your version of the solution, slightly modified:

public static void main(String[] args) {
    final String REGEX = "[-+]?[0-9]*\\.?[0-9]+";
    Scanner scanner = new Scanner(System.in);

    double number1 = 0;
    double number2 = 0;
    String operator;
    
    System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
    operator = scanner.next();

    System.out.print("Enter the first number: ");
    String num1 = scanner.next();

    System.out.print("Enter your second number: ");
    String num2 = scanner.next();
    scanner.close();

    boolean check1 = num1.trim().matches(REGEX);
    boolean check2 = num2.trim().matches(REGEX);

    if (check1 && check2) {
        number1 = Double.parseDouble(num1);
        number2 = Double.parseDouble(num2);
    }else {
        System.out.println("Only enter numbers not letters.");
    }

    String calculation;
    switch (operator) {
        case "+":
            calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
            break;
        case "-":
            calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
            break;
        case "*":
            calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
            break;
        case "/":
            calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
            break;
        default:
            calculation = operator + ":" + " Is not a valid operator!";
            break;
    }
    System.out.println(calculation);
}

The main differences are that I used only one Scanner object and that I replaced your nested if/else with a switch.

Below is a sample run

Enter the operator you would like to choose(+, -, *, /): +
Enter the first number: 5.5
Enter your second number: -7.2
5.5 + -7.2 = -1.7000000000000002

Other recommended improvements are:

  1. Loop until a valid operator is provided. There is no reason to wait until all inputs are provided to then determine the calculation cannot be done due to invalid operator.
  2. Do something similar to #1 above for each number.
  3. Use BigDecimal the calculation.
  4. Format the result to show however many decimal values you want to show.
hfontanez
  • 5,774
  • 2
  • 25
  • 37
0

The regular expression "^[0-9]+$" only evaluates to true for integers, because it checks whether the string consists of 0 - 9. If you want to check for doubles as well, this might help: https://www.baeldung.com/java-check-string-number

The first suggestion there is probably the easiest. Surround Double.parseDouble with a try catch, because it will give you an NumberFormatException if its not a number.