For Loop in Java
For Loop in Java. In this article we will look into how to create a for loop using the sample program below.
A For Loop consist of 3 main Structure, the initial value, the condition that keep the for loop going and iterating and the increment or decrements of the initial variable.
For Loop is widely use in all programming Language . it is one of the most important conditional statement to learn.
Let Step into the Sample program below to learn how to create a For Loop in Java
In this Sample Program it will ask the User whether he or she want to check out the Restaurant drink menu. If the Answer is yes, the Program will return the Drink Menu to the User. Well if the answer is “No” the program will greet the user and ask he or she to come again.
- As Usual we need to use the Scan Object to get the User Input, so we will need to “ import java.util.*;”
- Create a new scanner object called “inputscan1” this object will take in the User input
- Create the Drink Array Menu , and fill in the array content .here to learn how to create Array in Java
- Ask the User whether they want to check out the Restaurant drink menu
- If the Answer is “”y
- Create a for loop to loop through every single element contain inside every single Array and print out all the drinks reside in the arrat
- else if the answer is no. thank the User
package oop2; import java.util.*; public class Checkmenu { public static void main(String[] args) { Scanner inputscan1 = new Scanner(System.in); String[]drinkMenu={"Calamansi", "Green Tea","Soft Drink", "Ribena","Milo","OrangeJuice"}; System.out.println("How many choice of Drink the Restaurant have , to find out press (y) to Exit press (n) "); String srequest =inputscan1.nextLine(); if(srequest.contentEquals("y")){ for (int i=0; i<drinkMenu.length;i++){ System.out.println("The "+ i + " is " + drinkMenu[i]); } } else if (srequest.contentEquals("n")){ System.out.println("Come Again"); } else{ System.out.println("Come Another time"); } inputscan1.close(); } }
Check out the Oracle Library here is a useful resources to learn Java programming.