对不起菜鸟问题。这是我尝试 Java 编程的第一天。我需要帮助检索用户想要与整数一起使用的运算符的用户输入。
import java.util.Scanner;
public class calculator {
public static void main (String args[]) {
Scanner number = new Scanner(System.in);
double num1,num2,answer;
char operator;
System.out.println("Enter first number: ");
num1 = number.nextDouble();
operator = number.nextChar(); /* the "nextChar" is not correct */
System.out.println("Enter second number: ");
num2 = number.nextDouble();
if (operator = '+'){
answer = num1 + num2; /* If statements do not work like this */
} /* I would use "else if", unsure if it allows */
if (operator = '-'){
answer = num1 - num2;
}
if (operator = '*'){
answer = num1 - num2;
}
if (operator = '/'){
answer = num1 / num2;
}
System.out.println(num1 + num2 + operator + answer);
}
}
编辑版本:
import java.util.Scanner;
public class calculator{
public static void main (String args[]) {
Scanner userInput = new Scanner(System.in);
String operator;
double num1,num2,answer = 0;
System.out.println("Enter first number: ");
num1 = userInput.nextDouble();
System.out.println("Enter operator: ");
operator = userInput.next();
System.out.println("Enter second number: ");
num2 = userInput.nextDouble();
if (operator.equals ("+")){
answer = num1 + num2;
}
else if (operator.equals ("-")){
answer = num1 - num2;
}
else if (operator.equals ("*")){
answer = num1 * num2;
}
else if (operator.equals ("/")){
answer = num1 / num2;
}
System.out.println("First number:" + num1);
System.out.println("Operator:" + operator);
System.out.println("Second number:" + num2);
System.out.println("Answer: " + answer);
}
}
第一个数字:10.0
操作员:*
第二个数字:3.14
答案:31.400000000000002
非常感谢你们!帮助很大!