[英]Simple calculator is not printing the answer?
我的程序無法運行。 你覺得錯什么?
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = in.nextDouble();
System.out.print("Enter second number: ");
double num2 = in.nextDouble();
System.out.println("Enter operation to perform: ");
String oper = in.next();
if(oper == "add" || oper == "addition" || oper == "+") {
double sum = num1 + num2;
System.out.printf("The sum of the two numbers is %d", sum);
}
當我鍵入操作(它是一個字符串)時,程序終止。 輸出:
Enter first number: 12
Enter second number: 8
Enter operation to perform:
"add"
Process completed.
我似乎找不到錯誤,請幫忙?
切勿將字符串與運算符==
進行比較-這是一個粗略的錯誤。 使用equals
代替:
if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {
不要使用==
使用equals方法:
if(oper.equals("add") || oper.equals("addition") || oper.equals("+"))
==
運算符用於比較內存空間中的地址,而不是要比較的字符串的內容
不要使用==
比較字符串。 始終使用equals()
:
if("add".equals( oper ) || "addition".equals( oper ) || "+".equals( oper ) ) {
// ...
}
使用==
可以比較對象引用(或原始類型)。 字符串是Java中的對象,因此當您比較oper
和add
,它們都指向不同的對象。 因此,即使它們包含相同的值,與==
的比較也會失敗,因為它們仍然是不同的對象。
if(oper == "add" || oper == "addition" || oper == "+") {
應該
if(oper.equals("add") || oper .equals("addition") || oper.equals("+")) {
使用.equals
方法檢查兩個字符串是否有意義相等 , ==
運算符僅檢查兩個引用變量是否引用同一實例。
不要使用==
比較String
。 請改用equals
。
使用equals(..)
not ==
比較字符串
更換
if(oper == "add" || oper == "addition" || oper == "+") {
通過
if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {
==
比較相同參考而不是相同內容。
做到所有其他人都說的:使用equals
或equalsIgnoreCase
。 (對此有很好的解釋,所以在其他答案中也可以。在這里重復一遍是很愚蠢的。)
並且在控制台中鍵入“添加”,不帶“”。
只有兩者都起作用。
用這個
if("add".equals(oper) || "addition".equals(oper) || "+".equals(oper)) {
double sum = num1 + num2;
System.out.printf("The sum of the two numbers is %d", sum);
}
除了對字符串使用equals()
或更好的equalsIgnore()
代替==
,還需要在command-line
輸入add
而不是"add"
。
否則,您必須將其進行比較:
oper.equals("\"add\"")
另外,您似乎來自C
背景。 通常在Java中,將使用:
System.out.println("The sum of the two numbers is " + sum);
代替
System.out.printf("The sum of the two numbers is %d", sum);
因為%d
打印integer
數值而not double
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.