JAVA trim () does not work

Here is 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 this is not perfect, I just studied. However, trim () should work here ...

My input file:

 man, 300, 200, 3, 2, Bill 

If I were to add the trimmed string together, I should get:

 man30020032Bill 

But I get:

 man 300 200 3 2 Bill 

I have no idea why. Can anyone help?

+7
java trim
source share
4 answers

Lines are immutable. this is:

 myString.trim(); 

creates and returns a new trimmed string, but does nothing for the original string referenced by myString. Since a new line is never assigned to a variable, it remains hanging and will eventually be garbage. To get and use the trimmed string, you 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(); 
+9
source share

Edit

 for (int i = 0; i < readString.length; i++) { readString[i].trim(); } 

to

  for (int i = 0; i < readString.length; i++) { readString[i] = readString[i].trim(); } 

because String objects are immutable, and therefore the trim() method returns a new instance, which you must assign to the array.

+6
source share

Strings are immutable, so this does not change the contents of String :

 readString[i].trim(); 

Returns the changed value. Try

 readString[i] = readString[i].trim(); 
+6
source share

Strings in Java are immutable (they never change). Things like "trim ()" return new values ​​and do not update the current one.

Try:

 readString[i] = readString[i].trim() 
+4
source share

All Articles