English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Question:
Given the string variables name1 , name2 , and name3 , write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values).


My Answer:
if (name1.compareTo(name2) > 0)
{
if (name1.compareTo(name3) > 0)
max = name1;
}
else if (name2.compareTo(name1) > 0)
{
if (name2.compareTo(name3) > 0)
max = name2;
}
else if (name3.compareTo(name1) > 0)
{
if (name3.compareTo(name2) > 0)
max = name3;
}

2006-09-14 12:17:40 · 2 answers · asked by Anonymous in Computers & Internet Programming & Design

2 answers

What happens if name1 is the same as name2 or name3? Also, I assume you are elsewhere declaring "max" and you are later returning it.

You can also do this problem more succinctly:

if (name1.compareTo(name2) > 0) {
max = name1;
} else {
max = name2;
}

if (name3.compareTo(max) > 0) {
max = name3;
}

Or, even more compactly if you've been introduced to ternary expressions:

max = (name1.compareTo(name2) > 0) ? name1 : name2;
if (name3.compareTo(max) > 0) max = name3;

2006-09-14 14:16:37 · answer #1 · answered by Arthaey 2 · 0 0

String[] names = {name1, name2, name3};//or however you want to populate
String max;

Arrays.sort(names);//will use natural order (compareTo())
max = names[names.length-1];

2006-09-15 20:22:01 · answer #2 · answered by vincentgl 5 · 0 0

fedest.com, questions and answers