0
why doesn't it work?
3 Answers
+ 5
I assume that input is given on separate lines. Then do as follows:
double x = Double.parseDouble(sc.nextLine());
String u = sc.nextLine();
double y = sc.nextDouble();
The reason is the newline character at the end of the first number. The nextDouble() method does not consume newline characters, so the operator symbol in variable u ends up empty.
Now, string comparisons cannot be done using ==. It needs to be tested with help of the equals-method. The simplest way is to use a switch which uses the equals method behind the scenes:
double sum=0;
switch(u) {
case "+":
sum = x + y;
break;
case "-":
sum = x - y;
break;
case "/":
case ":":
sum = x / y;
break;
case "*":
sum = x * y;
break;
default:
System.out.print("Error");
}
The code can be done more elegantly, but i won't address that here as you will improve over time, so that is quite all right for a novice.
+ 1
Explain what the program needs to do, what input it needs to take, and someone will help. Alternatively look up the error on the internet and try to solve the problem
0
This is a calculator for two numbers. he should ask first the first number and then the sign (+,-,/,*) after that he asks for the second number and then gives a reply