Home > Software design >  how can i select a specify index from an array to use it in switch case
how can i select a specify index from an array to use it in switch case

Time:10-31

hi I'm beginner and i want to make a quiz math game how can i select a specify index of the random array and use it as case value.

                Random random=new Random();
                int num1= random.nextInt(30);
                int num2= random.nextInt(30);
    
                System.out.println(num1 " " num2 "=");
                int result=num1 num2;
    
                System.out.println("What is the answer of this operation?");
    
              int sugg1=random.nextInt(100);
              int sugg2=random.nextInt(100);
          
                int[] array = {sugg1,sugg2,result};
        
                Random rand = new Random();
        
                for (int i = 0; i < array.length; i  ) {
                    int randomIndexToSwap = rand.nextInt(array.length);
    
                    int temp = array[randomIndexToSwap];
    
                    array[randomIndexToSwap] = array[i];
    
                    array[i] = temp;
                }
                System.out.println(Arrays.toString(array));

                switch (Arrays.toString(array)) {
//I NEED HELP HERE HOW CAN I SELECT A SPECIFY INDEX OF THE RANDOM ARRAY AND USE IT AS CASE VALUE
               case array:
                
               }

CodePudding user response:

You can use switch(array[yourIndex]){case element: ...}

CodePudding user response:

I'm not sure to understand what you want to do..

Value version :

// Print for example [14,21,30] if question is 10 11
System.out.println(Arrays.toString(array));
// You want the user to select the answer
System.out.print("Please type the good answer : ");
Scanner scan = new Scanner(System.in);
switch(scan.nextInt()){
    case result:
        System.out.println("Good answer!");
        break;
    default:
        System.out.printtln("Bad answer!");
}

Index version :

// Print for example [14,21,30] if question is 10 11
System.out.println(Arrays.toString(array));
// You want the user to select the answer index
System.out.print("Please type the good answer : ");
Scanner scan = new Scanner(System.in);
int index = scan.nextInt();
if(index >= 0 && index <= array.length) {
    switch(array[index]){
        case result:
            System.out.println("Good answer!");
            break;
        default:
            System.out.printtln("Bad answer!");
    }
} else {
    System.out.println("Selected index does not exist in the array");
}

By the way, it could be good if sugg1 != sugg2 != answer, because in the following code it's not impossible that the values are the same :

int sugg1=random.nextInt(100);
int sugg2=random.nextInt(100);
int[] array = {sugg1,sugg2,result};
  • Related