4

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.

2
  • 1
    It would be better to use a Map for this purpose. Commented Mar 28, 2016 at 2:24
  • Please show your current code then we can base on that to help you. Commented Mar 28, 2016 at 2:33

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.