【发布时间】:2016-04-03 19:26:13
【问题描述】:
我刚开始用 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");
}
}
}
}
【问题讨论】:
-
是的,这是因为字符串上的“+”运算符是字符串连接。您需要转换为整数或双精度数,或其他任何值。还要注意溢出问题。除以整数可能不会达到您的预期,因此请考虑浮点数或双精度数。
标签: java text-based