如何輸入一個整體方程,如1 + 2。因爲我只能到目前爲止要求用戶輸入一個數字,我想知道我如何讓用戶輸入整個方程?在Java上創建一個基本的計算器?
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{
}
}
}
閱讀整行,然後解析String ... – Tom
請參閱http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form –
scan.nextLine() – Natecat