如何输入整个等式,如1 + 2.因为我只能要求用户一次输入一个数字,我想知道我如何让用户输入整个等式?
import java.util.Scanner;
public class TryCalculator {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Addition");
System.out.println("Subtraction");
System.out.println("Division");
System.out.println("Multiplication");
System.out.println("Natural Log");
System.out.println("Exponent");
System.out.println("**********************************");
Scanner scan = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
double value1;
double value2;
String op;
System.out.println("enter a digit");
value1 = scan.nextDouble();
System.out.println("enter operation ");
op = keyboard.next();
System.out.println("enter second digit");
value2 = scan.nextDouble();
if(op.equals("+")){
System.out.println(value1 + value2);
}if(op.equals("-")){
System.out.println(value1 - value2);
}if(op.equals("/")){
System.out.println(value1 / value2);
}if(op.equals("*")){
System.out.println(value1 * value2);
}if(op.equals("^")){
System.out.println(Math.pow(value1, value2));
}if (op.equals("log")){
System.out.println(Math.log(value1));
}else{
}
}
}
答案 0 :(得分:-1)
如果您不想使用javascript或某些评估者(link1,link2)
你可以用1 + 2
:
Scanner keyboard = new Scanner(System.in);
String exp = keyboard.next();
String []all = exp.split(" ", -1);
/*
then
all[0] = first operation;
all[1] = operator;
all[0] = second operator
*/
//and you can do like this
void calculate(String []all) {
Double value1 = Double.parseDouble(all[0]);
Double value2 = Double.parseDouble(all[2]);
String op = all[1];
if(op.equals("+")){
System.out.println(value1 + value2);
}if(op.equals("-")){
System.out.println(value1 - value2);
}if(op.equals("/")){
System.out.println(value1 / value2);
}if(op.equals("*")){
System.out.println(value1 * value2);
}if(op.equals("^")){
System.out.println(Math.pow(value1, value2));
}if (op.equals("log")){
System.out.println(Math.log(value1));
}else{
}
}
这未经过测试,但可以作为一个很好的起点。