【问题标题】:Text-Based Calculator not working基于文本的计算器不起作用
【发布时间】: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


【解决方案1】:

您正在尝试添加两个字符串。这只会将字符串彼此相邻。如果要添加它们,则需要先将它们解析为双打。试试:

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

【讨论】:

  • 虽然这种方法解决了加法问题(模溢出问题),但请注意代码有除法空间,整数除法不会按预期执行。
【解决方案2】:

您需要将String 转换为int 值以进行加法运算。做这样的事情:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 2017-09-19
    • 2016-11-10
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多