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

时间:2016-04-03 19:26:14

标签: 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");
            }
        }
    }
}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

您需要将String转换为int值才能添加。做这样的事情:

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