简体   繁体   中英

What would I need to return from this 2D String method?

So what does this method need to return to give me the desired results? An array or a 2D array?

I've tried changing String temp into an array like String[][] but I'm hit with more errors.

// The method 
public static String[][] Shuffle (String[][] states){  
       for ( int i = 0; i < states.length; i++){
            for (int j = 0; j <states[i].length; j++){
               int i1 = (int)(Math.random() * states.length);
               int j1 = (int) (Math.random() * states[i].length);

               String temp = states[i][j];
               states[i][j] = states[i1][j1];
               states[i1][j1] = temp;

               return temp;
          }
       }
    }

My code currently works without randomizing the first row in the array but I'd like to randomize the states. The new method would replace this line states[index][1] .

I think you're code is too complicated, and your method isn't named well.

Try this:

/**
 * @return a random [state, capital]
 */
static String[] getRandomState(String[][] states){  
     return states[(int)(Math.random() * states.length)];
}

and this:

String[] state = getRandomState(states);

System.out.println("What is the capital of " + state[0] + "?");

// get user input as user_ans

gamecounter++;
if (user_ans.equalsIgnoreCase(state[1])) {
    System.out.println("Correct!");
    correct_ans++;
} else {
    System.out.println("Incorrect! The correct answer is " + states[1]);
}
System.out.println();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM