简体   繁体   English

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

[英]Text-Based Calculator not working

I just started writing this basic text-based calculator in Java and I found into a problem when I ran the adding portion, when I add 2 numbers, say '9' and '9', the answer comes out to 99 instead of 18, as it should. 我刚开始用Java编写这个基于文本的基本计算器,当我运行加法部分时发现一个问题,当我将2个数字相加,例如“ 9”和“ 9”时,答案是99,而不是18,正如它应该。 Is it because I'm not storing integers, I'm storing the user's input as strings. 是因为我没有存储整数,而是将用户的输入存储为字符串。 Thank you, I appreciate any help. 谢谢,谢谢您的帮助。 As you can probably tell, I'm rather new to coding. 如您所知,我是编码的新手。

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

You are trying to add two strings. 您正在尝试添加两个字符串。 This will just put the strings next to each other. 这只会使字符串彼此相邻。 If you want to add them you need to parse them as doubles first. 如果要添加它们,则需要先将它们解析为双精度。 Try: 尝试:

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

You need to convert the String to an int value for the addition. 您需要将String转换为int值以进行加法运算。 Do something like this: 做这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM