I am just playing with Java.I'm trying to force my program to only accept 3 digit numbers. I believe I have successfully done this using a while loop (please correct me if I'm wrong). But how do I go about printing an error statement if the user enters a string. eg: "abc".
My code:
import java.util.Scanner;
public class DigitSum {
public static void main(String[] args) {
Scanner newScan = new Scanner(System.in);
System.out.println("Enter a 3 digit number: ");
int digit = newScan.nextInt();
while(digit > 1000 || digit < 100)
{
System.out.println("Error! Please enter a 3 digit number: ");
digit = newScan.nextInt();
}
System.out.println(digit);
}
}
How about this?
public class Sample {
public static void main (String[] args) {
Scanner newScan = new Scanner (System.in);
System.out.println ("Enter a 3 digit number: ");
String line = newScan.nextLine ();
int digit;
while (true) {
if (line.length () == 3) {
try {
digit = Integer.parseInt (line);
break;
}
catch (NumberFormatException e) {
// do nothing.
}
}
System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
line = newScan.nextLine ();
}
System.out.println (digit);
}
}
regexp version:
public class Sample {
public static void main (String[] args) {
Scanner newScan = new Scanner (System.in);
System.out.println ("Enter a 3 digit number: ");
String line = newScan.nextLine ();
int digit;
while (true) {
if (Pattern.matches ("\\d{3}+", line)) {
digit = Integer.parseInt (line);
break;
}
System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
line = newScan.nextLine ();
}
System.out.println (digit);
}
}
Embed the code for Reading the int in try catch block it will generate an exception whenever wrong input is entered then display whatever message you want in catch block
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With