1

我正在编写一个 Java 程序,在该程序中我根据字符串检查列表,然后对其进行处理。在fortran中,我会写一些类似的东西

where(list(:)==stringToCheck){
    ...
    statements
    ...
    }

相反,我对一堆 for 循环感到头疼,if 语句和中断到处都是。不,也许我可以稍微整理一下代码,但它仍然感觉比 fortran 效率低得多。

编辑,这是我使用的代码:

for(int idx=0;idx<player.get_charactersOwned().size();idx++)
            {
                if(player.get_charactersOwned().get(idx).get_characterName().equals(charName))
                {
                    /* Add character to the game
                     * Add game to the character*/
                    System.out.println("Character "+charName+" Found ");
                    gameToMake.addCharacters(player.get_charactersOwned().get(idx));
                    player.get_charactersOwned().get(idx).addGame(gameToMake);
                    break;
                }else 
                {
                    System.err.println("Character "+ charName +" not found");
                    System.out.println("Shall I add that Character? y/n ");
                    choice = scanner.nextLine();
                    if(choice.equalsIgnoreCase("y"))
                    {
                        charName = scanner.nextLine();
                        Character character = new Character(charName);
                        characterTempList.add(character);
                        player.addCharacter(characterTempList);
                        gameToMake.addCharacters(player.get_charactersOwned().get(idx));
                        player.get_charactersOwned().get(idx).addGame(gameToMake);
                        break;
                    }else{break;}
                }
            }

尽管修复此代码很诱人,但我更愿意使用变通方法。

在不使用外部库的情况下,是否有与此等效的 Java?

4

1 回答 1

2

不,Java 中没有等价物。相反,如果您需要检查一个字符列表(每个都有一个名称)是否包含一个字符名称,那么只需执行以下操作:

// search the name
boolean found = false;
for (Character c : player.get_charactersOwned()) {
    if (c.get_characterName().equals(charName)) {
        found = true;
        break;
    }
}

// perform the check
if (found) {
    // do something
} else {
    // do something else
}

顺便说一句,Character这对你的类来说是个坏名字,它与 Java 自己的Character类发生冲突。如果可能,重命名它,以避免混淆。或者,循环可以这样写:

boolean found = false;
for (int i = 0, n = player.get_charactersOwned().size(); i < n && !found; i++) {
    Character c = player.get_charactersOwned().get(i);
    if (c.get_characterName().equals(charName)) {
        found = true;
    }
}
于 2012-07-11T09:23:08.537 回答