1
import java.util.Scanner;

public class Improvedd {
    public static void main (String[] args) {

        Scanner input = new Scanner (System.in);

        int operand1 = Integer.parseInt (input.nextLine());
        char expo1 = input.next().charAt (0);
        int operand2 = Integer.parseInt (input.nextLine());
        String expression = "operand1 + expo1 + operand2";

        // how would I make it so the program ask for a math function
        // Like just let them enter 1/2 and get the printed result
        // I don't understand how I could just get the string to equal 
        // what I've placed

        System.out.println ("Enter expression: ");
        String expression = input.nextLine ();

        System.out.println (operand1 + expo1 + operand2 + "=");

        // if (expo1 == '/'  && operand2 == '0') {
        // System.out.println ("Cannot divide by zero"); }
        // how could I fix this expression

        if (expo1 == '-') {
            System.out.println (operand1-operand2);
        } else 
        if (expo1 == '+') {
            System.out.println (operand1+operand2);
        } else
        if (expo1 == '/') {
            System.out.println (operand1/operand2);
        } else 
        if (expo1 == '%') {
            System.out.println (operand1%operand2);
        }
        else{
            System.out.println ("Error.Invalid operator.");
        }
    }
}

我想要做的是让输入数学运算出现并让他们输入操作是 /、% 等,但我希望他们像 2/2 或 3%2 一样输入它并获得打印结果为 2/2=1 或 3%2=1。我遇到的真正麻烦是设置字符串,我不明白如何设置它。

4

1 回答 1

0

根据操作拆分输入。使用正则表达式拆分所有操作% * + - /

String regex = "(?<=op)|(?=op)".replace("op", "[-+*/()]"); 
String[] tokens = expression.split(regex);

//The equation
System.out.println (tokens[0] + tokens[1] + tokens[2] + "=");

int operand1 = Integer.parseInt(tokens[0]);
int expo1 = tokens[1]
int operand2 = Integer.parseInt(tokens[2]);

//If-else ladder or the switch-case to evaluate the operation and results.
于 2013-10-08T04:35:56.797 回答