2016-12-17 21 views
-1

我是新來的Java和我想編碼計算器。數字不計算,我不知道爲什麼會發生。Java新手試圖編碼一個計算器

這裏是我的代碼:

import java.util.Scanner; 

public class Calculator { 
    public static void main(String[] args){ 

     System.out.println("Type in any 2 numbers: "); 
     Scanner math = new Scanner(System.in); 
     int number = math.nextInt(); 
     int num2 = math.nextInt(); 

     System.out.println("Which operation would you like to use? (+,-,*,/)"); 
     String oper = math.next(); 

     if (oper == "+"){ 
      int total = number + num2; 
      System.out.println(total); 
     } 
     else if (oper == "-"){ 
      int total = number - num2; 
      System.out.println(total); 
     } 
     else if (oper == "*"){ 
      int total = number * num2; 
      System.out.println(total); 
     } 
     else if (oper == "/"){ 
      int total = number/num2; 
      System.out.println(total); 
     } 
    } 

} 

回答

1

你應該使用equals方法在Java中比較字符串。 當你在類中使用「==」時,它僅比較參考而不是數值。 這應該有這方面的工作解決

public class Calculator { 
    public static void main(String[] args){ 

     System.out.println("Type in any 2 numbers: "); 
     Scanner math = new Scanner(System.in); 
     int number = math.nextInt(); 
     int num2 = math.nextInt(); 

     System.out.println("Which operation would you like to use? (+,-,*,/)"); 
     String oper = math.next(); 

     if (oper.equals("+")){ 
      int total = number + num2; 
      System.out.println(total); 
     } 
     else if (oper.equals("-")){ 
      int total = number - num2; 
      System.out.println(total); 
     } 
     else if (oper.equals("*")){ 
      int total = number * num2; 
      System.out.println(total); 
     } 
     else if (oper.equals("/")){ 
      int total = number/num2; 
      System.out.println(total); 
     } 
    } 
+0

謝謝!這工作。 – Ubermench

0

@Ran Koretzki是正確的,我對你的代碼的一種可能的改進。您正在閱讀來自用戶的輸入並分配給「整數」值。即使此代碼不會提示編譯時或運行時錯誤,您的代碼中也存在邏輯問題。

您正在分割兩個整數並將結果分配給一個整數。當你試圖分割兩個整數並且沒有餘數時,這種方法很有效。但是如果在劃分過程中有剩餘的話,你將會失去這個餘數或分數。爲了解決這個問題,你應該把你的輸入讀成雙精度值,並把運算結果賦值爲雙精度值。