Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I want to know how can I rewrite this code using a while loop instead of a do-wh

ID: 3838509 • Letter: I

Question

I want to know how can I rewrite this code using a while loop instead of a do-while and how to replace the try/catch with something more simpler.

public static int getValidInt(String prompt, int min, int max) {
String number = "";
int n = 0;
do {
try {
System.out.print(prompt);
nStr = kb.next();

// Convert string to int
n = Integer.parseInt(nStr);

if ((n < min) || (n > max))
System.out.println("ERROR: " + nStr + " is not in the valid range (1...4)");

} catch (NumberFormatException nfe) {
System.out.println("ERROR: " + nStr + " is not a valid integer (1...4)");
}
} while ((n < min) || (n > max));

return n;
}

}

Explanation / Answer

You can do as below, the only difference between do while and while is that do while make sure it run at least once and here if we replace it with while, it will perform the same operation as we are not expecting any min and max from user. And to replace try catch we can use if else and print error message if number is not in range

public static int getValidInt(String prompt, int min, int max) {

String number = "";
int n = 0;

   while((n<min) || (n >max))
   {
   System.out.print(prompt);
nStr = kb.next();
// Convert string to int
n = Integer.parseInt(nStr);
   if( (n<min) || (n > max))
   {
   System.out.println("ERROR: " + nStr + " is not in the valid range (1...4)");
   }
     
   else
   {
   //perform required action
   }
  
   }

   return n;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote