如果用户没有输入给定类型的操作之一,我正在尝试制作一个简单的计算器并在尝试使其显示“错误”时继续在标题中显示错误。
import java.util.Scanner;
public class experiments {
public static void main(String args[]) {
Scanner userInput = new Scanner(System.in);
String operation;
double fNum, sNum, ans;
//select type of operation
System.out.println("Type addition, subtraction, multiplication, or division, then press enter");
operation = userInput.nextLine();
if (operation!=("addition","subtraction","multiplication","division")) {
System.out.println("error");
}
//enter numbers
System.out.println("Enter first number");
fNum = userInput.nextDouble();
System.out.println("Enter second number");
sNum = userInput.nextDouble();
//calculate
if (operation.equals("addition")) {
ans=fNum + sNum;
}
else if (operation.equals("subtraction")) {
ans=fNum - sNum;
}
else if (operation.equals("multiplication")){
ans=fNum * sNum;
}
else if (operation.equals("division")) {
ans=fNum/sNum;
}
//print answer
System.out.println("The answer is ");
System.out.println(ans);
}
}