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