Search code examples
javaarrayssortingsubstringnames

Counting characters before a ',' in each index of array, and returning the highest


I need to get the longest surname from this array and return it.

String[] names = {"Turner, Brendan", "Savage, Fred", "Zidy, Boop",
                 "Zobie, Brendan", "Flurb, Fred", "Mopeeeeeyyy, Boopertinson"};

So far I have this;

public static void getLongestSurname(String[] name){
         int i = 0;
         int x = 0;
         int currentLength = 0; 
         int lastLength = 0; 
         String longestName = null;
    for(int j = 0; j < (name.length); j++){
      
          while (name[j].charAt(i) != ',') {
          i++;
          currentLength++;
          }
      System.out.println(i);
      System.out.println("current is"+currentLength);
      i = 0;
      currentLength = 0;
        if ( currentLength > lastLength ){
           longestName = name[i]; 
          }
    }
    
     System.out.println("longest surname should be; "+ longestName);
  }

but the output it gives is "longest surname should be; Turner, Brendan" which isn't the longest name in the list.

I'm doing something wrong here, but my brain feels like scrambled egg at this point. Can anyone help?

thank you.


Solution

  • You need to keep track of the longestName while iterating all names, compare the length of current name with length of current longestString instead of comparing with lastLength

    longestName will be updated if length of currentName is greater than length of longestNumber

    Solution

    public static void getLongestSurname(String[] name){
            
            int currentLength = 0; 
            int lastLength = 0; 
            String longestName = null;
            for(int j = 0; j < (name.length); j++){
    
               // split string by "," to get surname
                String[] strAr = name[j].split(",");
                // length of current surname 
                currentLength = strAr[0].length();
               // compare length of current surname with longest surName                
                if ( currentLength > lastLength ){
                    longestName = name[j]; 
                    lastLength = strAr[0].length();
                }
            }
    
            System.out.println("longest surname should be; "+ longestName);
        }