2013-10-16 64 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);