> Alright.
>
> the length will tell me the lengths of each of those
> strings.
>
> But how can compare those lengths with each other and
> be returned with a result that tells me that
> mystring[2] is the largest string?
With some if-statements: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/if.html
Please try it yourself first. If you run into problems, post your code here (using code tags*) and explain what the problem is.
* http://forum.java.sun.com/help.jspa?sec=formatting
I gave it a go, and what I came up with didn't quite work. Can you guys find what i'm missing here thanks.
public class StringTest
{
public static void main (String [] args)
{
String[] k = new String[10];
int indexMaxLength = 0;
int i;
k[0] = "asdfasdfasdfasdfasdfasdfasdfasdf";
k[1] = "asdfasdf";
k[2] = "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdf";
k[3] = "asdfasdfasdfasdf";
k[4] = "asdfasdfasdfasdfasdf";
k[5] = "asdfasdfasdfasdfasdfasdf";
k[6] = "adsdf";
k[7] = "adsdf";
k[8] = "asdfasdfasdfasdfasdfasdfasdfasdfasdf";
k[9] = "asdfasdfasdfasdfasdfasdfasdf";
for(i = 0; i < k.length; i++)
{
if(k[i].length() > k[indexMaxLength].length())
{
indexMaxLength = i;
}
}
System.out.println(i);
}
}
you're right, it works now.
'I kind of get how it's working.
But if someone doesn't mind explaining what's going on, can you explain what's going on?
I see that as i is incrementing, it is being compared to the length of the string at 0, and if it is greater than that, then that 0 becomes whatever i is. But still confuses me..
You're the one who wrote it. Kind of odd that you'd want others to explain it to you.
Personally I would have done it this way:
String[] stuff = // do something to fill stuff with Strings of varying length
// and for simplicity assume length of the array > 1, and no position in the array is null
int longest = 0;
for (int i = 1; i < stuff.length; i++)
if (stuff[i].length() > stuff[longest].length())
longest = i;
> Personally I would have done it this way:
> > String[] stuff = // do something to fill stuff with
> Strings of varying length
> // and for simplicity assume length of the array > 1,
> and no position in the array is null
> int longest = 0;
> for (int i = 1; i < stuff.length; i++)
>if (stuff[i].length() > stuff[longest].length())
>longest = i;
>
I'm sorry, I don't see the difference - are you suggesting your version for readability? Because I think that comes way after understanding the fundamentals behind the code...
> I'm sorry, I don't see the difference -
I don't see the difference anymore either. I think I had somehow confused two different threads. Apologizes for any confusion.
> are you suggesting your version for readability? Because I
> think that comes way after understanding the
> fundamentals behind the code...
I'm not convinced there's a difference between readability and understanding the fundamental structure and algorithm in the code.