Using loop and a half repetition control to test terminating the loop after execution loop body in while loop. We learned and took an example of while statement however, loop and a half repetition enables us to test terminating loop in the middle of loop body. This is an example of a java program which asks user to enter name and if the name length is less than or equal one character will display an error message.
import java.util.*;
public class halfLoop
{
public static void main(String [] args)
{
String EnterName; // Entered by user
Scanner scan = new Scanner(System.in);
System.out.print("Type name ");
EnterName = scan.next();
while (EnterName.length() <= 1) // Value length less than or equal one
{
System.out.println("Invalid entry "); // Print Invalid entry
System.out.println("Type name ")
EnterName = scan.next();
if (EnterName.length() > 1)break; // break to stop if value bigger than 1
}
}
}
As the above example inside the loop body we used ( if ) to determine loop terminating and actually it is the half repetition control to put limit for this repetition or it will be an infinite loop, unable to stop. In the above example we used scanner class in the package java.util to read string and it is not difficult, but we may want to take other ways to show or get results in the program by using GUI Input and output. This is the second example with prompt message dialog.
import javax.swing.*;
public class You_Java
{
public static void main(String []args)
{
String name;
name = JOptionPane.showInputDialog(null,"Type name ");
while (name.length() <= 1)
{
JOptionPane.showMessageDialog(null,"Invalid Entry ");
name = JOptionPane.showInputDialog(null,"Type name ");
if (name.length() > 1)break;
}
}
}
import javax.swing.*;
public class You_Java
{
public static void main(String []args)
{
String name;
name = JOptionPane.showInputDialog(null,"Type name ");
while (name.length() <= 1)
{
JOptionPane.showMessageDialog(null,"Invalid Entry ");
name = JOptionPane.showInputDialog(null,"Type name ");
if (name.length() > 1)break;
}
}
}
0 comments:
Post a Comment