How to compare String components in two different arrays (Java)

I am building a type of game (at least what it is now) ... and basically, I want someone to play a game to enter the province (yes, I'm Canadian) and its capital and to tell them if they did it right.

Out.,

array1[ ] = {ontario, manitoba, saskatchewan};
array2[ ] = {toronto, winnipeg, regina};

I want to encode it so that if component 1 of array 1 is equal to component 1 of array2, it is correct. Sorry, I'm kind of new to java and this site.

+4
source share
2 answers

You can use the card for this purpose. The following snapshot implements lowercase map states in their capitals.

Map<String,String> stateCapital = new HashMap(){{
        put("ontario","toronto");
        put("manitoba","winnipeg");
        put("saskatchewan","regina");
    }}; 

stateName sate, _ , , :

stateCapital.get(stateName.toLowerCase()).equalsIgnoreCase(capitalName)

statenames capitals , .

+3

. HashMap, , . . , , - :

for (int i = 0; i < array1.length; i++) {
    if (userInput.compareTo(array2[i]) == 0) {
        return correctAnswer;
    }
}
+1

All Articles