简体   繁体   中英

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

I'm constructing a type of game (at least that's what it is right now...) and basically, I want whoever is playing the game to enter a province (yes I'm Canadian) and its capital and the program to tell them if they did so correctly.

Ex.,

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

I want to code it in such a way that if component 1 of array1 is equal to component 1 of array2, it's correct. Sorry, I'm kind of new to java and this site.

You can use a Map for this purpose. The following snipped implements map states in lower case to their capital cities.

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

If stateName indicates the name of the sate and capitalName indicates the name of the capital, you can verify the combination by the boolean value returned by expression:

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

If you already have all the statenames and capitals in arrays, you can put them in the map.

I agree with the previous answers. A HashMap is probably best for your purposes. However, you can still do it with an array. I'm not sure how you want to do your game, but you could try something like this:

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

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