2016-04-24 28 views
0

如何輸入一個整體方程,如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{ 

     } 
    } 
} 
+0

閱讀整行,然後解析String ... – Tom

+1

請參閱http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form –

+0

scan.nextLine() – Natecat

回答

-1

如果你不想使用JavaScript或一些評估像那些(link1link2) 你可以像這樣用簡單的語句,比如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{ 

    } 
} 

這不是測試,但可以是一個很好的起點。

+1

*「這沒有測試」*顯然。所以測試它並修復bug(s):)。 – Tom

+0

一些想法在某些場合綽綽有餘。我不必編寫他的所有應用程序。 –

+0

*「我不必編寫他的所有應用程序。」*誰說你應該? – Tom