特此附上我的代码供您参考。当我为乘法功能执行以下代码时,我收到以下错误,
线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:choice2.main(choice2.java:99) 处的 -4
仅供参考 - 该程序适用于该程序中的所有其他功能。
代码 :
import java.util.*;
class choice2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner S = new Scanner(System.in);
int ch, subch;
String Target = null;
int codePos = 0, a, b, c = 0;
String[] Arith = {"Add", "Sub"};
String[] Mult = {"Multiplication", "Division", "Modulas" };
System.out.println("1.Arithmatic");
System.out.println("2.Mult/Div/Mod");
System.out.println("0 to Exit from Menu");
System.out.println("Enter your Choice");
ch = S.nextInt();
switch (ch) {
case 1:
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("9.Goback to Main Menu");
subch = S.nextInt();
if (subch == 1)
Target = "Add";
else
Target = "Sub";
codePos = Arrays.binarySearch(Arith, Target);
switch (Arith[codePos]) {
case "Add":
System.out.println("Enter value for A");
a = S.nextInt();
System.out.println("Enter value for B");
b = S.nextInt();
c = a + b;
System.out.println("The result is " + c);
break;
case "Sub":
System.out.println("Enter value for A");
a = S.nextInt();
System.out.println("Enter value for B");
b = S.nextInt();
c = a - b;
System.out.println("The result is " + c);
break;
}
break;
case 2:
System.out.println("1.Multiplication");
System.out.println("2.Division");
System.out.println("3.Modulas");
System.out.println("9.Goback to Main Menu");
subch = S.nextInt();
switch (subch) {
case 1:
Target = "Multiplication";
break;
case 2:
Target = "Division";
break;
case 3:
Target = "Modulas";
break;
default:
System.out.println("Invalid Value");
}
System.out.println(codePos);
System.out.println(Target);
// codePos = Arrays.binarySearch(Mult, Target);
codePos = Arrays.binarySearch(Mult, 0, Mult.length, Target);
switch (Mult[codePos]) {
case "Multiplication":
System.out.println("Enter value for A");
a = S.nextInt();
System.out.println("Enter value for B");
b = S.nextInt();
c = a * b;
System.out.println("The result is " + c);
break;
case "Division":
System.out.println("Enter value for A");
a = S.nextInt();
System.out.println("Enter value for B");
b = S.nextInt();
c = a / b;
System.out.println("The result is " + c);
break;
case "Modulas":
System.out.println("Enter value for A");
a = S.nextInt();
System.out.println("Enter value for B");
b = S.nextInt();
c = a % b;
System.out.println("The result is " + c);
break;
}
}
System.out.println("Exit from program");
}
}