If Else Conditional Statement

Open fire

You can display individual invaders using an If Else conditional statement. This syntax will allow you to print only the invaders stipulated by the invnumber variable. Notice that the == sign is used instead of the = sign when making a comparison. Change the invnumber, compile the class, and execute the program a few times to verify that the conditional statement is working.

Notice the use of the import statement at the top of the code. This statement brings in the System.out method from the Java API so that you no longer need to type "System" when you wish to print.

This code illustrates the use of a conditional If Else statement.

  1. //imports the System.out method from the Java API (application programming interfaces)
  2. import static java.lang.System.out;
  3. public class DemoIfElse {
  4. public static void main(String[] args) {
  5. //Declares string values
  6. String firstinv = "The first invaders were the Romans.";
  7. String secondinv = "The second invaders were the Anglo-Saxons.";
  8. String thirdinv = "The third invaders were the Jutes.";
  9. String fourthinv = "The fourth invaders were the Vikings.";
  10. String fifthinv = "The fifth invaders were the Normans.";
  11. int invnumber = 4;
  12. if (invnumber == 1) {
  13. out.println();
  14. out.println(firstinv);
  15. }
  16. else if (invnumber == 2) {
  17. out.println();
  18. out.println(secondinv);
  19. }
  20. else if (invnumber == 3) {
  21. out.println();
  22. out.println(thirdinv);
  23. }
  24. else if (invnumber == 4) {
  25. out.println();
  26. out.println(fourthinv);
  27. }
  28. else if (invnumber == 5) {
  29. out.println();
  30. out.println(fifthinv);
  31. }
  32. else {
  33. out.println();
  34. Java codeout.println("The number is invalid.");
  35. }
  36. }
  37. }

Use Save As to save the code to your folder as: DemoIfElse.java. Then compile the code in the Command prompt window. Use javac DemoIfElse.java to create the .class file. Execute the program. Use java DemoIfElse to run the program.

Your output should look like this:

c:\javamike>java EnglandInvaders

The fourth invaders were the Vikings.

 

< Invaders (Array) Switch (Case) >