LOOP in JAVA cont… JAVA by Ravinder Nath Rajotiya - April 16, 2021April 16, 20210 Loop Controls Here is an example of range validation, but has no control as how many times the user can take to input the correct value Example-1: Input Validation package com.example; import javax.swing.*; public class loopContinued { public static void main(String[] args) { //input validation String input; int number; input= JOptionPane.showInputDialog("Please enter a number" + "between 1 and 100"); number=Integer.parseInt(input); // now let us validate while(number <1 || number >100) // OR operator to check outside range { JOptionPane.showMessageDialog(null, "Not a valid number"); input=JOptionPane.showInputDialog("Please enter a number between 1 and 100"); number = Integer.parseInt(input); } } } Example-2: user control of Loop In the example below, we use control the loop variable package com.example; import javax.swing.*; public class loopContinued { public static void main(String[] args) { //input validation String input; int Maxnumber; input=JOptionPane.showInputDialog("How high should I go to square the number"); Maxnumber = Integer.parseInt(input); System.out.println("number Squareed "); for(int i=1; i<= Maxnumber; i++) { System.out.println( i
Introduction to Loop in JAVA JAVA by Ravinder Nath Rajotiya - April 16, 2021April 16, 20210 Loops in JAVA There are three types f loop structures in JAVA What is a Loop? A Loop is a squance of instructions that are continually repeated until a certain condition is reached or met. We have following three types of loop in JAVA. while() do- while() for loop Requirements of loop We require to follow the following steps for writing a loop: for every loop we need a loop control variable with some initializatio value give final test value to this variable inside the loop e.g. while(x<10) Write the body of the loop containing the task to be repeated and inside the loop modify or change the control variable to test for changed value next time the loop executes. Let us start with the loop This