Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA trim() not working [duplicate]

Tags:

java

trim

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?

like image 561
JesseWoodring Avatar asked Nov 18 '13 17:11

JesseWoodring


1 Answers

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();
like image 177
Hovercraft Full Of Eels Avatar answered Nov 15 '22 19:11

Hovercraft Full Of Eels