Reading in a text file and comparing text - Java
In my program I am reading in and parsing a file for resources.
I extract a string which represents the resource type, do a simple if then else statement to check if it matches any known types and throw an error if it doesn't:
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() + "|");
}
开发者_C百科
Ignoring my bad naming and non descript exception, this statement is always going to the final else, even if type IS "spritesheet" as read in from the file, etc.
java.lang.Exception: Invalid Resource File - Invalid type: |spritesheet|
at Resource.Load(Resource.java:55) //Final else.
If I set type to "spritesheet" before this call, it works, so I'm wondering if it's some kind of encoding error or something?
I haven't done much work in java so I might be missing something simple :)
Assuming type
is a String, you want to use String.equals() to test for equality. Using the == operator tests to see if the variables are references to the same object.
Also, to make your life easier, I would suggest using String.equalsIgnoreCase() as this will save you from calling toLowerCase()
.
Starting from Java 7 you can use Strings in switch statements! :)
The following should work:
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() + "|");
}
I haven't tried it yet, let me know how it goes!
精彩评论