Reputation: 1013
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);
}
}
Upvotes: 3
Views: 60839
Reputation: 35
You want an Exception to occur if the user enters a string such as 'abc' instead of an integer value then the InputMismatchException
is right for you.
Let me give a basic example for you.
public static void main(String[] args)
{
Scanner ip = new Scanner(System.in);
int a;
System.out.println("Enter Some Input");
try{
a = ip.nextInt();
}
catch(InputMismatchException msg){
System.out.println("Input Mismatch Exception has occured " + msg.getMessage());
}
}
Upvotes: 1
Reputation: 11
How I would do it is using an if statement. The if statement should be like this:
if(input.hasNextInt()){
// code that you want executed if the input is an integer goes in here
} else {
System.out.println ("Error message goes here. Here you can tell them that you want them to enter an integer and not a string.");
}
Note: If you want them to enter a string rather than an integer, change the condition for the
if statement to input.hasNextLine()
rather than input.hasNextInt()
.
Second Note: input
is what I named my Scanner. If you name yours pancakes then you should type pancakes.hasNextInt()
or pancakes.hasNextLine()
.
Hope I helped and good luck!
Upvotes: 1
Reputation: 192
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);
}
}
Upvotes: 3
Reputation: 3288
Here nextInt
method itself throws an InputMismatchException
if the input is wrong.
try {
digit = newScan.nextInt()
} catch (InputMismatchException e) {
e.printStackTrace();
System.err.println("Entered value is not an integer");
}
This should do.
Upvotes: 2
Reputation: 17839
You can check if a String is of numeric value in the following ways :
1) Using a try/Catch Block
try
{
double d = Double.parseDouble(str);
}catch(NumberFormatException nfe) {
System.out.println("error");
}
2) Using regex
if (!str.matches("-?\\d+(\\.\\d+)?")){
System.out.println("error");
}
3) Using NumberFormat Class
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
if(str.length() != pos.getIndex()){
System.out.println("error");
}
4) Using the Char.isDigit()
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)){
System.out.println("error");
}
}
You can see How to check if a String is numeric in Java for more info
Upvotes: 0
Reputation: 1050
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
Upvotes: 2
Reputation: 33143
When you grab the input or pull the input string run through parseInt
.
This will in fact throw an exception if yourString
is not an Integer
:
Integer.parseInt(yourString)
And if it throws an exception you know its not a valid input so at this point you can display an error message. Here are the docs on parseInt
:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
Upvotes: 0