3

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);
       }
    }
sakthisundar
  • 3,278
  • 3
  • 16
  • 29
binary101
  • 1,013
  • 3
  • 23
  • 34

7 Answers7

3

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);
    }
}
Ruzia
  • 192
  • 5
  • This is perfect. Thanks very much. Its exactly what i was trying to achieve. Thanks to everyone though. All your answers are valid. This one works better for me though :D – binary101 Oct 11 '12 at 11:53
  • "Integer.parseInt()" is not essence. You are able to use regexp instead of "Integer.parseInt()". – Ruzia Oct 11 '12 at 12:33
  • Look at your answer Ruzia, you used `Integer.parseInt()` I think thats very essence (whatever the heck that means). Also why did you downvote my answer considering you took it? – JonH Oct 11 '12 at 12:56
  • Who me? I haven't down voted anybody.I only just understand the Integer.parseInt(). Not sure what regexp means... – binary101 Oct 11 '12 at 13:07
  • > JonH I think essence is while loop code. "Integer.parseInt()" is one of the option. – Ruzia Oct 11 '12 at 13:30
2

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

Software Sainath
  • 1,040
  • 2
  • 14
  • 39
2

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.

sakthisundar
  • 3,278
  • 3
  • 16
  • 29
1

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!

shaneod
  • 49
  • 1
  • 7
anonymous
  • 11
  • 1
1

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());
        }
    }
sakyan
  • 35
  • 1
  • 7
0

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)

JonH
  • 32,732
  • 12
  • 87
  • 145
0

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

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125