我剛開始在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");
}
}
}
}
是的,這是因爲字符串上的「+」運算符是字符串連接。你需要轉換爲整數或雙打,或任何其他。請注意溢出問題。用整數劃分可能不會達到你所期望的,所以考慮花車或雙打。 – KevinO