-1

我需要一个在命令提示符下充当计算器的 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");
        }
    }
}
4

1 回答 1

0

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

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

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");
    }
}
于 2013-10-29T02:47:02.160 回答