-1

this code is designed to initialise an array C and its values, then print them and print the largest string within the array. i have used an enhanced for loop. the debug showed an error that 'longest name' was not initialised so i added =null to it when declaring the string but the output of the program always prints null now rather than the longest string in the array please help!

package week14;

public class LabArray {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int [] A = new int[5];
        int [] B = new int[5];
        String [] C = {"luke", "elliot", "glenn", "jonny", "jack"};
        int [] D = new int[5];
        int length = C[1].length();
        String longestname;
        int nextlength;
        for (String name: C){
        System.out.println(name);
            nextlength = name.length();
            System.out.println(name.length());
            if (nextlength > length){
                length = nextlength;
                 longestname = name;
            }
        }
        System.out.println("\nthe longest word in the array = " + longestname);
    }
}
1

2 Answers 2

2

for initial value in the length you assign the second element of the array which is already the String with the biggest size(elliot) ,so you never getting inside the if loop and you never assign a value to longestname,

Initialize the value of the longestname as well

int length = C[1].length();
String longestname=C[1];
Sign up to request clarification or add additional context in comments.

5 Comments

It would be cleaner to just start the length at zero, but this also works.
should i not initialise the above two variables at the [0] array address?
You can use any of the array's element for initial value,but the standard way is to use the first element
@DonRoby ,what if the array had only empty Strings? you gotta think all the possibilities
Indeed you're right. You definitely should also start the value at the empty string if you're going to start the length at zero.
0

THis code works perfectly :

    int [] A = new int[5];
    int [] B = new int[5];
    int [] D = new int[5];        
    String [] C = {"luke", "elliot", "glenn", "jonny", "jack"};       
    String longestname=null;
    int maxlength=0;
    for(String max:C)
    {
        if(maxlength<max.length())
        {
            maxlength=max.length();
            longestname=max;
        }
    }
    System.out.println("\nthe longest word in the array = " + longestname);

output :

run:

the longest word in the array = elliot
BUILD SUCCESSFUL (total time: 0 seconds)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.