抱歉这个菜鸟问题。这是我尝试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
非常感谢!帮了很多忙!
答案 0 :(得分:0)
在比较中使用==,而不是=(这意味着分配)。
答案 1 :(得分:0)
正如其他人已经指出的那样,使用==
运算符来检查是否相等。 =
运算符将改为赋值。
要阅读Scanner
中的单个字符,请查看以下问题:Scanner method to get a char。在那里你会发现使用Scanner.findInLine()
方法的建议,它接收正则表达式作为参数。提供.
通配符作为模式,您将能够获得包含下一个字符的字符串,并在其上使用charAt(0)
,您将获得char
。
Scanner sc = new Scanner("abc");
char ch = sc.findInLine(".").charAt(0);
System.out.println(ch); // prints "a"
当然,您也可以使用Scanner.next()
将下一个单词作为String,并获取其第一个字符。但是考虑到这样做会从输入缓冲区丢弃其余部分。
答案 2 :(得分:0)
确定。这有效,可以帮助您走向java
public class Tester4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double num1, num2, answer = 0;
String operator;
System.out.println("Enter first number: ");
num1 = input.nextDouble();
System.out.println("Enter operator: ");
operator = input.next();
System.out.println("Enter second number: ");
num2 = input.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);
}
}
答案 3 :(得分:-1)
您需要使用
if (operator == '+')
注意'double等于'。