Suresh Kumar B
Suresh Kumar B

Reputation: 11

Nested switch with different expression types: ArrayIndexOutOfBoundsException -4

I am herewith enclosing my code for your reference. while I am executing the below code for the multiplication functionality,i am getting the below error,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -4 at choice2.main(choice2.java:99)

FYI - The program is working fine for all other functionalities in this program.

Code :

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");
    }
}

Upvotes: 0

Views: 249

Answers (4)

user949300
user949300

Reputation: 15729

While the other answers that the array needs to be sorted are correct, they miss a point. Consider these lines:

codePos = Arrays.binarySearch(Mult, 0, Mult.length, Target);
switch (Mult[codePos]) {
  case "Multiplication":
  .....
}

Why are you searching the array using a String, Target, to get an index, then getting back the String from the array that matched? That accomplishes basically nothing (except allows for bugs). Far simpler to just go

switch (Target) {
  case "Multiplication":
   ...
  default: // handle any mistypings here...
}

Upvotes: 1

Reimeus
Reimeus

Reputation: 159794

The line

switch (Mult[codePos]) {

is throwing an ArrayIndexOutOfBoundsException as codePos is -4 from the previous search due to the fact that the input String array is not ordered for the binary search

codePos = Arrays.binarySearch(Arith, Target);

From the docs

index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length

Therefore codePos becomes

- (array.length + 1) = -4

Binary searches values rely on their values to be ordered. Therefore you need

String[] Mult = { "Division", "Modulas", "Multiplication", };

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Here

 codePos = Arrays.binarySearch(Mult, 0, Mult.length, Target);// will retuen codePos as -4. 

So you can change

 codePos = Arrays.binarySearch(Mult, 0, Mult.length, Target)

By

            List<String>   list=Arrays.asList(Mult);
            codePos = list.indexOf(Target);

Upvotes: 0

Brian
Brian

Reputation: 17309

Arrays.binarySearch returns a negative number if it can't find the value. Also, to use a binary search, the array has to be sorted, which it's not, which is probably causing your error. Declare your array like so:

String[] Mult = {"Division", "Modulas", "Multiplication" };

Upvotes: 3

Related Questions