7

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?

JesseWoodring
  • 75
  • 1
  • 5

4 Answers4

9

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();
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
6

Change

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 that you must assign to the array.

René Link
  • 48,224
  • 13
  • 108
  • 140
6

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

readString[i].trim();

It returns the changed value. Try

readString[i] = readString[i].trim();
rgettman
  • 176,041
  • 30
  • 275
  • 357
4

Strings in Java are immutable (they never change). Things like 'trim()' return new values, and don't update the current one.

Try:

readString[i] = readString[i].trim()
rolfl
  • 17,539
  • 7
  • 42
  • 76