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
Switch Case in JAVA JAVA by Ravinder Nath Rajotiya - April 15, 2021April 16, 20210 Decision Making using switch case statement Well you have seen the decision making in previos posts on if, if-else statements. switch case is yet another pwerful decision making concept. We first ask the user to input some number, alphabet or some string to be used in taking decision so that control can be transferred at some relevant place in the program. //JOptionPane.showInputDialog() gets only inputs string values, to make them numbers we need to convert it to integer as: input = JOptionPane.showInputDialog("Please enter 1, 2, or 3"); //convert to integer number=Integer.parseInt(input) //for for inputting single character, we don't convert string to letters, but read only first letter of string at position '0'. This is becaues strings are constructed using characters input = JOptionPane.showInputDialog("Please enter a, b, or