java - 基于文本的计算器不起作用

标签 java text-based

我刚刚开始用 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");
            }
        }
    }
}

最佳答案

您正在尝试添加两个字符串。这只会将字符串放在一起。如果你想添加它们,你需要首先将它们解析为 double 。尝试:

            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);

关于java - 基于文本的计算器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390061/

相关文章:

java - JSP 打印主机名

c++ - 如何在 C++ 中实现随机多响应

用于基于文本的游戏的 Python GUI 工具包?

Java score积分自动递增

java - 如何将 ArrayList<String> 传递给 bean

java - Dialog 内的 RecyclerView 底部被截断

python - 我可以创建 RPG 风格的保存并退出,然后重新加载进度吗?

java - 将 'If' 语句的部分内容留空(快速简单的问题)

从点的数组列表中进行java圆识别