if
statements are not limited to two cases. You can
combine an else
and an if
to make an
else if
and test a whole range of mutually exclusive
possibilities. For instance, here's a version of the Hello program
that handles up to four names on the command line:
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
if (args.length == 0) {
System.out.println("Hello whoever you are");
}
else if (args.length == 1) {
System.out.println("Hello " + args[0]);
}
else if (args.length == 2) {
System.out.println("Hello " + args[0] + " " + args[1]);
}
else if (args.length == 3) {
System.out.println("Hello " + args[0] + " " + args[1] + " " + args[2]);
}
else if (args.length == 4) {
System.out.println("Hello " + args[0] +
" " + args[1] + " " args[2] + " " + args[3]);
}
else {
System.out.println("Hello " + args[0] + " " + args[1] + " " args[2]
+ " " + args[3] + " and all the rest!");
}
}
}
You can see that this gets mighty complicated mighty quickly. No experienced Java programmer would write code like this. There is a better solution and you'll explore it in the next section.