I just started to code for fun and tried to make a basic calculator, but I got a problem.
There is my code at the bottom
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
double temp1, temp2;
int temp4 = 1;
int end = 0;
**String temp3,temp5;**
calculator cal = new calculator();
Scanner scan = new Scanner(System.in);
while(end==0){
System.out.println("Please put your first number to calculate");
temp1 = scan.nextDouble();
System.out.println("Please put your second number to calculate");
temp2 = scan.nextDouble();
System.out.println("What arithmetic operation you want to do?(+,-,/,*)");
**temp3 = scan.nextLine();**
if(temp3.equals("+")){
System.out.println("Result is" + cal.add(temp1, temp2));
}
else if(temp3.equals("-")){
System.out.println("Result is" + cal.subtract(temp1, temp2));
}
else if(temp3.equals("*")){
System.out.println("Result is" + cal.multiply(temp1, temp2));
}
else if(temp3.equals("/")){
System.out.println("Result is" + cal.divide(temp1, temp2));
}
else
System.out.println("You got wrong operator");
while(temp4==1){
System.out.println("Now you want to quit(press y/n)");
temp5 = scan.nextLine();
if(temp5.equals("y")){
temp4=0;
end=1;
}
else if(temp5.equals("n")){
System.out.println("Then here we go again");
temp4=0;
}
else
System.out.println("You put wrong words");
}
}
}
}
I can't understand why temp3 didn't work.
I wanted to check I made mistake, so I made temp5 but it works.
Can anyone explain why?
The problem is that nextDouble()
doesn't use up the new line character used when entering the second double
. So nextLine()
sees the newline already present and consumes it.
Add in an extra nextLine()
call to consume the newline from the second number.
temp2 = scan.nextDouble();
// Add consuming of new line here.
String dummy = scan.nextLine();
System.out.println("What arithmetic operation you want to do?(+,-,/,*)");
temp3 = scan.nextLine();
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.