2013-10-16 152 views
0

我希望程序接受操作符號(+, - ,*,/)作爲輸入。每當我這樣做,它會引發異常。任何人都可以幫助我解決這個問題,並讓程序接受這些標誌之一作爲輸入。輸入計算器程序

import java.lang.*; 
import java.util.*; 

public class Calculator 
{ 
    private double solution; 
    private static double x, y; 
    private static char ops; 

    public static interface Calculate 
    { 
     public abstract double operation(double x, double y); 
    } 

    public static class addition implements Calculate 
    { 
     public double operation(double x, double y){ 
     return(x+y); 
     } 
    } 

    public static class subtraction implements Calculate 
    { 
     public double operation(double x, double y){ 
     return(x-y); 
     } 
    } 

    public static class multiplication implements Calculate 
    { 
     public double operation(double x, double y){ 
     return(x*y); 
     } 
    } 

    public static class division implements Calculate 
    { 
     public double operation(double x, double y){ 
     return(x/y); 
     } 
    } 

    public void calc(int ops){ 
     Scanner operands = new Scanner(System.in); 

     System.out.println("operand 1: "); 
     x = operands.nextDouble(); 
     System.out.println("operand 2: "); 
     y = operands.nextDouble(); 

     System.out.println("Solution: "); 

     Calculate [] jumpTable = new Calculate[4]; 
     jumpTable['+'] = new addition(); 
     jumpTable['-'] = new subtraction(); 
     jumpTable['*'] = new multiplication(); 
     jumpTable['/'] = new division(); 

     solution = jumpTable[ops].operation(x, y); 

     System.out.println(solution); 
    } 

    public static void main (String[] args) 
    { 
     System.out.println("What operation? ('+', '-', '*', '/')"); 
     System.out.println(" Enter 0 for Addition"); 
     System.out.println(" Enter 1 for Subtraction"); 
     System.out.println(" Enter 2 for Multiplication"); 
     System.out.println(" Enter 3 for Division"); 

     Scanner operation = new Scanner(System.in); 
     ops = operation.next().charAt(0); 

     Calculator calc = new Calculator(); 
     calc.calc(ops); 
    } 
} 

該錯誤是

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43 
at Calculator.calc(Calculator.java:54) 
at Calculator.main(Calculator.java:76) 
+3

你覺得'jumpTable ['+']'是做什麼的? –

回答

1
jumpTable['+'] 

將被翻譯到+符號(它轉換爲一個char)的ASCII碼(43),還剩下一些出來的0-4的範圍。您可能想要使用實際的數字索引(或者確保您的數組可以包含您的char值集合的最高數字表示形式,在本例中爲/)。

ASCII table

enter image description here

+0

謝謝。我把它轉換成了ASCII碼,但是我忘了讓jumpTable的容量大於47.在Calculate [] jumpTable = new Calculate [4]中將4更改爲50;'修復了問題。 –

0

只能通過0..3索引引用jumpTable。但是你試圖通過超出這個範圍的'+'符號來引用它。考慮使用HashMap<String, Calculate>以這種方式存儲操作:

Map<String, Calculate> jumpTable = new HashMap<String, Calculate>(); 
jumpTable.put("+", new addition()); 
jumpTable.put("-", new subtraction()); 
jumpTable.put("*", new multiplication()); 
jumpTable.put("/", new division()); 

String operation = Character.toString((char) ops); 
solution = jumpTable.get(operation).operation(x, y);