ZephyrX
ZephyrX

Reputation: 37

can't print according to value in CSV

I want to print lines in command line based on the values in csv, this is my code:

public static void view() throws IOException, FileNotFoundException {
        String path = "C:\\Users\\hayth\\eclipse-workspace\\pouch\\src\\pouch\\temp.csv";
        String line ="";
        
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(path));
            removeBlank(path);
            while((line = bufferedReader.readLine()) != null) {
                String[] values = line.split(",");              
                if(values[0].trim() == "pencil") {
                    System.out.println("Item: " + values[0] + " \tBrand: " + values[1] + " \tLength: " + values[2]);
                } else if(values[0].trim() == "eraser"){
                    System.out.println("Item: " + values[0] + " \tBrand: " + values[1] + " \tShape: " + values[2]);
                } else {
                    System.out.println("Item: " + values[0] + " \tBrand: " + values[1] + " \tState: " + values[2]);
                }
                
                
            }
        } finally {
            if( bufferedReader != null) {
                bufferedReader.close();
            }
        }
    }

as you can see different objects have different properties so the line I want to print should be different for each case, like pencil has brand and length, eraser has brand and shape and so on.

sample csv:

pencil,XX,10
eraser,YY,rectangle
sharpener,YY,new
pencil,YY,12

but the output I'm getting is:

Item: pencil    Brand: XX       State: 10
Item: eraser    Brand: YY       State: rectangle
Item: sharpener         Brand: YY       State: new
Item: pencil    Brand: YY       State: 12

I can see that I'm not able to compare the values from the array values and it's executing the else statement but I cannot seem to understand the problem. I'm fairly new to Java and any help would be greatly appreciated. Thanks :)

Upvotes: 0

Views: 34

Answers (1)

zzevannn
zzevannn

Reputation: 3724

Change your values[0].trim() == "whatever" lines to values[0].trim().equals("whatever") or better yet, equalsIgnoreCase. == tests if the strings reference the same object, not if their values are equivalent.

Also, see String.equals versus ==

Upvotes: 1

Related Questions