If Else Conditional Statement
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.
- //imports the System.out method from the Java API (application programming interfaces)
- import static java.lang.System.out;
- public class DemoIfElse {
- public static void main(String[] args) {
- //Declares string values
- String firstinv = "The first invaders were the Romans.";
- String secondinv = "The second invaders were the Anglo-Saxons.";
- String thirdinv = "The third invaders were the Jutes.";
- String fourthinv = "The fourth invaders were the Vikings.";
- String fifthinv = "The fifth invaders were the Normans.";
- int invnumber = 4;
- if (invnumber == 1) {
- out.println();
- out.println(firstinv);
- }
- else if (invnumber == 2) {
- out.println();
- out.println(secondinv);
- }
- else if (invnumber == 3) {
- out.println();
- out.println(thirdinv);
- }
- else if (invnumber == 4) {
- out.println();
- out.println(fourthinv);
- }
- else if (invnumber == 5) {
- out.println();
- out.println(fifthinv);
- }
- else {
- out.println();
- out.println("The number is invalid.");
- }
- }
- }
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.