迷失了弦乐

时间:2013-10-08 04:22:05

标签: java arrays string math expression

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

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

1 个答案:

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