Here's what I have:
public void readFile(String fileToOpen) {
File myFile = new File(fileToOpen);
try {
Scanner inFile = new Scanner(myFile);
while (inFile.hasNext()) {
String input = inFile.nextLine();
String [] readString = input.split(",");
for (int i = 0; i < readString.length; i++) {
readString[i].trim();
}
System.out.println(readString[0] + readString[1] + readString[2] + readString[3] + readString[4] + readString[5]);
Point myPoint = new Point(Integer.parseInt(readString[1]), Integer.parseInt(readString[2]));
if (readString[0].toLowerCase().equals("man")) {
Man myMan = new Man(myPoint, Integer.parseInt(readString[3]), Integer.parseInt(readString[4]), readString[5]);
this.myList.add(myMan);
} else if (readString[0].toLowerCase().equals("woman")) {
Woman myWoman = new Woman(myPoint, Integer.parseInt(readString[3]), Integer.parseInt(readString[4]), readString[5]);
this.myList.add(myWoman);
} else {
inFile.close();
throw new IllegalArgumentException();
}
}
inFile.close();
}
I know its not perfect, I'm just learning. However, trim() should be working here...
My input file is:
man, 300, 200, 3, 2, Bill
If I was to add the trimmed string together, I should get:
man30020032Bill
But I am getting:
man 300 200 3 2 Bill
I have no idea why. Can anyone help please?
Answer
Strings are immutable. this:
myString.trim();
creates and returns a new trimmed String, but does nothing to the original String referred to by myString. Since the new String is never assigned to a variable, it is left hanging and will be garbage collected eventually. To obtain and use the trimmed String must assign the result to a variable, such as the original variable (if desired):
myString = myString.trim();
So in your case:
readString[i] = readString[i].trim();
No comments:
Post a Comment