2014-07-12 66 views
-1

我正在使用Eclipse中的一個小型計算器,用戶在此輸入方程式如1 + 1。但是,我不確定如何讓用戶輸入更復雜的方程式,如1 + 2 * 3/4在Java計算器中允許多個輸入

另外,如果用戶試圖輸入一個不是有效等式的字符串,我想要出現一個錯誤。這裏是我的代碼:

public static double addition(double x, double y) // The Addition Operation 
{ 
    double add = x + y; 
    return add; 
} 

public static double subtraction(double x, double y) // The Subtraction Operation 
{ 
    double sub = x - y; 
    return sub; 
} 

public static double division(double x, double y) // The Devision Operation 
{ 
    double div = x/y; 
    return div; 
} 

public static double multiplication(double x, double y) // The Multiplication Operation 
{ 
    double multi = x * y; 
    return multi; 
} 

public static double factorial(double x) // The Factorial (F!) 
{ 
    double result = 1; 
    while (x > 1) 
    { 
     result = result * x; 
     x = x - 1; 
    } 
    return result; 
} 

static Scanner scanner = new Scanner(System.in); // a Global Scanner. 

public static void main(String[] args) 
{ 
    double numb1, numb2; 
    char operation; 
    System.out.println("Enter Your Equation: "); 

    // Split string by space 
    String[] parts = scanner.nextLine().split(""); 

    // Convert to corresponding types 
    operation = parts[1].charAt(0); 

    switch (operation) 
    { 
     case '+': 
      numb1 = Integer.parseInt(parts[0]); 
      operation = parts[1].charAt(0); 
      numb2 = Integer.parseInt(parts[2]); 
      System.out.println("The Product is: " + addition(numb1, numb2)); 
      break; 

     case '-': 
      numb1 = Integer.parseInt(parts[0]); 
      operation = parts[1].charAt(0); 
      numb2 = Integer.parseInt(parts[2]); 
      System.out.println("The Product is: " + subtraction(numb1, numb2)); 
      break; 
     case '*': 
      numb1 = Integer.parseInt(parts[0]); 
      operation = parts[1].charAt(0); 
      numb2 = Integer.parseInt(parts[2]); 
      System.out.println("The Product is: " + multiplication(numb1, numb2)); 
      break; 
     case '/': 
      numb1 = Integer.parseInt(parts[0]); 
      operation = parts[1].charAt(0); 
      numb2 = Integer.parseInt(parts[2]); 
      System.out.println("The Product is: " + division(numb1, numb2)); 
      break; 
     case '!': 
      numb1 = Integer.parseInt(parts[0]); 
      operation = parts[1].charAt(0); 
      System.out.println("The Product is: " + factorial(numb1)); 
    } 
} 
+0

我建議使用一些正則表達式規則來分割大字符串與運營商的許多數字.. http://www.dreamincode.net/forums/topic/236807-regex-use-for-a-simple-calculator-應用/ 這可能對你有所幫助 – HackerGK

+0

對於「加法」方法的註釋'//加法操作'是完全不需要的

+0

@ l19但是......但是,你會如何知道它的作用? –

回答

5

有一些簡單的方法已經評價Java中的表達,但假設這是學習的目的:

解析數學公式的最棘手的部分是佔的順序操作 - 也就是說,你不能只是遍歷公式並逐點計算它(在這種情況下,像3 + 2 * 5就會失敗)。

你在找什麼是解析中綴表達式的方法;關於該主題的部分here將引導您瞭解您必須完成的基本概念。這裏沒有Java代碼,但是它會從中獲得樂趣,對吧?

+0

aha ok,感謝您的幫助 –