Java & J2EE Page 3 - Conditionals, Expressions and Other Java Operators |
Since the beginning of time man has been asking these important questions: Can a homo sapien beat up a homo erectus? Can a man beat a saber-toothed tiger? Can a saber-toothed tiger defeat a giant sloth? Will Jessie Jackson ever become president? Did Bill Clinton ever have relations with that woman? When you have a lot of Ifs, you need to build yourself a good old fashioned If Else If statement. Look at the beautiful and pertinent one below: class SuperHero { public static void main(String[]) { int hulk = 9; int daredevil = 10; int batman = 11; int wolverine = 8; String winner = "Whoever"
if(daredevil > hulk && daredevil > batman && daredevil > wolverine) winner = "Daredevil is the winner!"; else if(hulk > daredevil && hulk > batman && hulk > wolverine) winner = "The Incredible Hulk is the winner!"; else if(batman > daredevil && batman > hulk && batman > wolverine) winner = "Batman is the winner!!"; else if(wolverine > hulk && wolverine > daredevil && wolverine > batman) winner = "Wolverine is the winner!"; else winner = "Nobody wins!"; System.out.println(winner);
} } The above code is for a battle royal amongst the super heroically inclined. Each hero is assigned a numeric value and then compared to each other hero. Whichever hero has the highest value gets stored in the winner category. In this case, the winner is Batman, and the following prints to the screen: Batman is the winner! If no one met the criteria (had a higher value than the other three super heroes), then the following would have been printed to the screen: Nobody wins!
blog comments powered by Disqus |
|
|
|
|
|
|
|