- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
How to implement if-else and for loop in Java ?
The following code is a simple Java program which plays a game called as "FitBit". It counts to 101, and on each count checks whether it is multiple of 3 or 7 or both. If it is multiple 3, it replaces it with fit. If it is multiple of 7, it replaces it with bit and if it is multiple of both 3 and 7, it replaces it with fitbit. The program performs all this tasks by the help of for loop, if-else construct and modulus operator. The class below contains a method named as main. It’s the starting point for any application to execute. I will also provide you with the source code below. Here is the code :
package com.hubberspot.example; public class FitBitGameDemo { public static void main(String[] args) { // count from 1 to 101 for(int counter = 1; counter <= 101; counter++) { // If it is a multiple of 3 & 7 if (((counter % 3) == 0) && ((counter % 7) == 0)) { System.out.print("fitbit"); } // If it is a multiple of 3 else if ((counter % 3) == 0) { System.out.print("fit"); } // If it is a multiple of 7 else if ((counter % 7) == 0) { System.out.print("bit"); } // If it is not a multiple of 3 or 7 else { System.out.print(counter); } System.out.print(" "); } } }
for loop starts with a initial value and loops till boolean condition is false. The for loop follows three steps to execute, such as :
1. Initialization :- In the initialization step, a variable gets initialized. This variable is responsible for the number, till for loop gets executed. It gets initialized with a initial value from which for loop starts.
2. Test Condition :- In the test condition step, after each execution of for loop a condition is tested by taking in account the variable created above. This test condition returns back a boolean value such as true or false. If the condition is true, for loop continues to execute. If the condition is false, for loop terminates. The control statement proceed to statement just after the for loop.
3. Increment :- As soon as a particular loop ends, the variable created in step 1 is either incremented or decremented. The increment / decrement of variable decides the test condition result in the step 2. This step help in deciding whether for loop can continue to loop or not.
if - else makes a decision based on whether a condition is true or false.
Output of the program -
If - else statement in Java
for loop in Java
Watch my complete Youtube channel below -
- Java Hubberspot - YouTube
Hello friends, I am Dinesh Varyani. Owner of blog http://www.hubberspot.com . This channel will have Java Programming Tutorials for beginners ... Visit my Ja...