简体   繁体   English

如何比较两个不同数组中的String组件(Java)

[英]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. 我想以这样的方式对其进行编码:如果array1的组件1等于array2的组件1,那么它是正确的。 Sorry, I'm kind of new to java and this site. 对不起,我是java和这个网站的新手。

You can use a Map for this purpose. 您可以使用Map来实现此目的。 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: 如果stateName指示sate的名称而capitalName指示大写的名称,则可以通过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. HashMap可能最适合您的用途。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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