2014-09-19 10 views
1

有工作代碼如何使這個單一變量成(NAMEA或名稱B或NameC)

else if (command.equalsIgnoreCase("noclip") && !playerName.equalsIgnoreCase("Tom")) { 
      PlayerHandler.messageToAll = (playerName 
        + " tried to noclip and has been autobanned!"); 
      appendToBanned(playerName); 
      disconnected = true; 

,因爲它說,不等於湯姆,我是誰可以使用的只有一個命令。但是,我想爲此命令添加多個用戶。

我想說以下,但它不工作...我怎麼會正確地說這(java)?

else if (command.equalsIgnoreCase("noclip") && !playerName.equalsIgnoreCase("Tom" || "Tommy" || "Mod Tom")) { 
      PlayerHandler.messageToAll = (playerName 
        + " tried to noclip and has been autobanned!"); 
      appendToBanned(playerName); 
      disconnected = true; 
+0

您使用某種類型的集合。在這個特定的情況下,'HashSet'似乎是一個不錯的選擇。 – Mephy 2014-09-19 06:28:35

+1

這將是最好有一個用戶/播放器對象和playerName.equalsIgnoreCase(player.getName())或如果player.isPlayer(用戶名)..但解決您當前的問題&&(playerName.equalsIgnoreCase(「湯姆」)| | playerName.equalsIgnoreCase(「Tommy」)) – 2014-09-19 06:31:04

+1

我建議檢查用戶權限,而不是用戶。然後將用戶放入組中。所以你可能有一個組「noclippers」並添加用戶。然後你會檢查用戶是否在noclippers組(如果該組有權利的話)。 – Fildor 2014-09-19 06:31:45

回答

0

您不能使用!playerName.equalsIgnoreCase("Tom" || "Tommy" || "Mod Tom"))||運營商用於比較boolean。您可以考慮以下三種方法:

if (/* Previous conditions && */ (!playerName.equalsIgnoreCase("Tom") || 
     !playerName.equalsIgnoreCase("Tommy") || 
     !playerName.equalsIgnoreCase("Mod Tom"))) 
    // do things 

或使用循環使用數組:

String[] admins = {"Tom", "Tommy", "Mod Tom"}; 
boolean matches = false; 
for (String name : admins) 
    if (name.equalsIgnoreCase(playerName)) 
     matches = true; 
if (/* Previous conditions && */ !matches) 
    // do things 

或使用一組:

HashSet<String> set = new HashSet<>(); 
set.add("Tom"); 
set.add("Tommy"); 
set.add("Mod Tom"); 
if (/* Previous conditions && */ !set.contains()) 
    // do things 
2

爲了簡化代碼位,我會將可能的用戶名放入HashSet

HashSet<String> names = new HashSet<String>(); 
names.addAll("Tom", "Tommy", "Mod Tom"); 

,然後我會檢查:

if (command.equalsIgnoreCase("noclip") && !names.contains(playerName)) { .. } 
相關問題