2011-07-30 52 views
1

在我的程序中,我正在閱讀和解析資源文件。閱讀文本文件並比較文本 - Java

我提取其指的是資源類型的字符串,做一個簡單的,如果檢查,然後else語句,如果它匹配任何已知的類型,如果它不拋出一個錯誤:

if(type.toLowerCase() == "spritesheet") { 
    _type = ResourceType.Spritesheet; 
} else if(type.toLowerCase() == "string") { 
    _type = ResourceType.String; 
} else if(type.toLowerCase() == "texture") { 
    _type = ResourceType.Texture; 
} else if(type.toLowerCase() == "num") { 
    _type = ResourceType.Number; 
} else { 
    throw new Exception("Invalid Resource File - Invalid type: |" + type.toLowerCase() + "|"); 
} 

無視我的壞命名和非DESCRIPT例外,這句話總是會最終否則,即使類型是從文件中讀取「spritesheet」等

java.lang.Exception: Invalid Resource File - Invalid type: |spritesheet| 
at Resource.Load(Resource.java:55) //Final else. 

如果我這個調用之前將類型設置爲「spritesheet」它的工作原理,所以我想知道如果這是某種編碼錯誤或什麼的?

我沒有做過Java中大量的工作,所以我可能失去了一些東西簡單:)

回答

7

假設type是一個字符串,你想用String.equals()測試相等。使用==運算符測試來查看變量是否是對同一對象的引用。

此外,爲了讓您的生活更輕鬆,我建議您使用String.equalsIgnoreCase(),因爲這樣可以使您免去撥打toLowerCase()的麻煩。

+1

知道這是愚蠢的,感謝:P – Blam

+0

@Blam我會認爲,大多數人至少做了一次......哎呀,我一直在做專業Java開發幾年,我仍然這樣做有時:) – Jon7

+0

與'=='一起使用'String'是捕獲新Java程序員的東西之一。由於字符串不可變性,編寫自包含程序時它通常可以正常工作,但除此之外它失敗了。 @Jon有正確的答案,應該被接受。下面是一些Java的樂趣......如果你將每個比較改爲'type.toLowerCase()。intern()== ...',你的代碼就可以工作。我並不是建議你這樣做,請關注你。 – Paul

2

從Java 7開始,您可以在switch語句中使用Strings! :)

下面應該工作:

switch (type.toLowerCase()) { 
    case "spritesheet": _type = ResourceType.Spritesheet; break; 
    case "string":  _type = ResourceType.String;  break; 
    case "texture":  _type = ResourceType.Texture;  break; 
    case "num":   _type = ResourceType.Number;  break; 

    default:    throw new Exception("Invalid Resource File " + 
         "- Invalid type: |" + type.toLowerCase() + "|"); 
} 

我還沒有嘗試過,讓我知道如何去!