1.6.3 Do while Loops

The contents of a Do While loop is always executed at least once. Therefore the boolean variable isNotAnInteger need not be set to true.

/**

* keep prompting for an integer until the user supplies one

* using an input dialog box ,try/catch and a boolean variable

* all with a while loop

*/

public int inputInteger(){

String prompt, str;

int num= 0;

boolean isNotAnInteger;

prompt = "Enter an integer: ";

do {

str = JOptionPane.showInputDialog(prompt,null);

try{

num = Integer.parseInt(str);

isNotAnInteger = false;

}

catch(NumberFormatException e){

isNotAnInteger = true;

prompt = "You MUST enter an integer: ";

}

}while (isNotAnInteger);

return num;

}