2016-04-03 62 views
0

我剛開始在Java中編寫這個基本的基於文​​本的計算器,當我運行添加部分時發現了一個問題,當我添加2個數字時,說'9'和'9',答案是99,而不是18,因爲它應該。是因爲我沒有存儲整數,我將用戶的輸入存儲爲字符串。謝謝,我感謝任何幫助。正如你可能知道的,我對編碼相當陌生。基於文本的計算器不工作

import java.util.Scanner; 
import java.lang.String; 

public class calc { 
    public static void main(String[] args) throws InterruptedException { 
     while (true) { 
      Scanner in = new Scanner(System.in); 
      System.out.println("Type in what you would like to do: Add, Subtract, Multiply, or Divide"); 
      String input = in.nextLine(); 
      if (input.equalsIgnoreCase("Add")) { 
       System.out.println("Type in your first number:"); 

       String add1 = in.nextLine(); 
       System.out.println("Type in your second number"); 
       String add2 = in.nextLine(); 

       String added = add1 + add2; 
       System.out.println("Your answer is:" + added); 
      } 
      else if(input.equalsIgnoreCase("Subtract")) { 
       System.out.println("Type in your first number:"); 
      } 
      else if(input.equalsIgnoreCase("Multiply")) { 
       System.out.println("Type in your first number:"); 
      } 
      else if(input.equalsIgnoreCase("Divide")) { 
       System.out.println("Type in your first number:"); 
      } 
      else { 
       System.out.println("This was not a valid option"); 
      } 
     } 
    } 
} 
+0

是的,這是因爲字符串上的「+」運算符是字符串連接。你需要轉換爲整數或雙打,或任何其他。請注意溢出問題。用整數劃分可能不會達到你所期望的,所以考慮花車或雙打。 – KevinO

回答

2

您需要將String轉換爲另外一個int值。做這樣的事情:

Integer result = Integer.parseInt(add1) + Integer.parseInt(add2)

3

您嘗試添加兩個字符串。這隻會把字符串放在一起。如果你想添加它們,你需要首先將它們解析爲雙打。嘗試:

  System.out.println("Type in your first number:"); 
      double add1 = Double.parseDouble(in.nextLine()); 
      System.out.println("Type in your second number"); 
      double add2 = Double.parseDouble(in.nextLine()); 

      double added = add1 + add2; 
      System.out.println("Your answer is:" + added); 
+0

雖然這種方法解決了附加問題(模數溢出問題),但請注意代碼有分區空間,並且整數除法不會按預期執行。 – KevinO

+0

@KevinO好點 - 編輯我的答案 – nhouser9