我附上我的代码供您引用。当我执行以下乘法功能代码时,我收到以下错误,
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: -4 在 choice2.main(choice2.java:99)
仅供引用 - 该程序对于该程序中的所有其他功能都运行良好。
代码:
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");
}
}
最佳答案
如果找不到该值,
Arrays.binarySearch
将返回负数。另外,要使用二分搜索,必须对数组进行排序,但事实并非如此,这可能会导致您的错误。像这样声明你的数组:
String[] Mult = {"Division", "Modulas", "Multiplication" };
关于java - 具有不同表达式类型的嵌套开关: ArrayIndexOutOfBoundsException -4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17660545/