Barley0421
Barley0421

Reputation: 1

Finding the largest string in the second column of a 2d array

I have a 2d array and I'm trying to find the largest string only in the second column of the 2d array, but for some reason it only gives me the first string in the 2nd column even if there is a bigger string. Here's what I have:

class Main{
    public static void main(String[] args) {
        
        String[][] data = {
            {"Jeep", "Wrangler", "35000"},
            {"Honda", "civic", "25000"},
            {"Toyota", "Corolla", "22000"}
        };

        
        LargestName(data);
    }

    public static void LargestName(String[][] a){
        String largestN = a[0][1];
        for(int i = 0; i < a.length; i++){
            if(largestN.compareTo(a[i][1])<0){ 
                largestN = a[i][1] + "";
            }
        }
        System.out.println(largestN);
    }    
}

Again, I'm trying to compare the strings only in the second column of the 2d array but with what I have it only gives me the first string of the 2nd column "Wrangler", even if there is a larger string in the 2nd column. Please help

Upvotes: 0

Views: 32

Answers (2)

notAPPP
notAPPP

Reputation: 300

You need to comapre length, compareTo is not good choice, please look what are you trying to do:

System.out.println("Wrangler".compareTo("civic"));
System.out.println("civic".compareTo("Corolla"));
System.out.println("Corolla".compareTo("Wrangler"));

result:

-12 32 -20

Upvotes: 0

queeg
queeg

Reputation: 9394

I cannot see a flaw in the code. So look at the definition of 'largest string': It is possible that the code really returns exactly that value that you chose in the beginning.

This can be easily tested by choosing a different start value.

On top of that you could add more System.out.println, or even better use a debugger to step through your code. This will give you a very good understanding of how the JVM executes your code.

Upvotes: 1

Related Questions