![](/img/trans.png)
[英]Java: try(Scanner scan = new Scanner(System.in) { } causing an exception
[英]how to scan for certain character with scanner(system.in)
我是Java編程的新手。 我試圖使計算器可以使用if語句執行4種基本數學運算。 但是我沒有按預期工作。 嘗試解析運算符時,它僅以else語句結束。
我想我的if語句格式不正確?
任何幫助是極大的贊賞。
謝謝。
import java.util.Scanner;
import java.lang.Object;
public class calc {
public static void main(String args[]) {
System.out.println("Test kalkulator za sabiranje");
Scanner keyboard = new Scanner(System.in);
double fnum, snum, res;
String ch = "";
System.out.println("Enter first number: ");
fnum = keyboard.nextDouble();
System.out.println("Enter operation: ");
ch = keyboard.next();
if( ch == "+") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum + snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "-") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum - snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "/") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum / snum;
System.out.println("Result is: "+ res);
}
else if( ch == "*") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum * snum;
System.out.println("Result is: "+ res);
}
else {
System.out.println("You entered wrong operator, please try again");
}
keyboard.close();
}
}
字符串對象是引用對象,這意味着您鍵入類似
str == "+"
您正在檢查內存中str所在的點是否等於+。 要驗證兩個字符串是否相等,您需要使用.equals方法,如下所示
str.equals("+")
而不是==
您應該使用equals
方法
您的代碼很好,問題是當您將ch
與字符串“ +”,“-”等進行比較時...
在Java中,字符串是對象。 如果對象引用相同的對象,則使用==
運算符比較對象只會返回true。 為了實際比較這兩個對象,您需要使用equals()
方法。
綜上所述,正確的條件應該是:
if(ch.equals("+")){ }
用於每個比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.