Java命令提示计算器 - 家庭作业

时间:2013-10-29 01:58:13

标签: java command-prompt

我需要一个Java程序,它在命令提示符中充当计算器。我可以拿出这个,但我必须一次输入一个问题(输入“2”,按下输入,输入“+”,按下输入,输入“2”,按下输入)我想知道我是否可以把它放在我可以放入“2 + 2”的位置。在此先感谢您的帮助!

import java.util.*;

public class memCalc
{
    public static void main (String args[])
    {
        Scanner input = new Scanner(System.in);
        String op;
        int numberOne, numberTwo, result = 0;
        numberOne = input.nextInt();
        op = input.next();
        numberTwo = input.nextInt();
        if (op.equals("+"))
        {
            result = numberOne + numberTwo;
            System.out.print("The answer is: " + result + " .\n");
        }
        else if (op.equals("-"))
        {
            result = numberOne - numberTwo;
            System.out.print("The answer is: " + result + " .\n");
        }
        else if (op.equals("*")) 
        {
            result = numberOne * numberTwo;
            System.out.print("The answer is: " + result + " .\n");
        }
        else if (op.equals("/"))
        {
            result = numberOne / numberTwo;
            System.out.print("The answer is: " + result + " .\n");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这不是最好的解决方案......但它确实有效。基本上我只是将用户输入的整个东西放入一个String中,然后找到运算符的位置,然后我使用操作的位置找到2个数字并将它们放入int中。之后,我使用substring将运算符放入String中。然后,这就是你得到的。

这不是最好的代码......但是这有助于

public static void main (String args[])
{
    Scanner input = new Scanner(System.in);
    String equation = input.nextLine();
    int opLocation = equation.indexOf("+");
    if(opLocation == -1)
    {
        opLocation = equation.indexOf("-");
    }
    if(opLocation == -1)
    {
        opLocation = equation.indexOf("*");
    }
    if(opLocation == -1)
    {
        opLocation = equation.indexOf("/");
    }
    String number = equation.substring(0,opLocation);
    int numberOne = Integer.parseInt(number);
    number = equation.substring(opLocation + 1);
    int numberTwo = Integer.parseInt(number);
    String op = equation.substring(opLocation,opLocation+1);
    int result;
    if (op.equals("+"))
    {
        result = numberOne + numberTwo;
        System.out.print("The answer is: " + result + " .\n");
    }
    else if (op.equals("-"))
    {
        result = numberOne - numberTwo;
        System.out.print("The answer is: " + result + " .\n");
    }
    else if (op.equals("*")) 
    {
        result = numberOne * numberTwo;
        System.out.print("The answer is: " + result + " .\n");
    }
    else if (op.equals("/"))
    {
        result = numberOne / numberTwo;
        System.out.print("The answer is: " + result + " .\n");
    }
}