2

This is a small part of my program that I am working on. I'm trying to check if the user enters the correct number.

They have five choices to choose from so they can either hit 1, 2, 3, 4, or 5. Then press enter.

So I want to check to make sure the user doesn't type anything in < 1 or > 5. I got that part to work... But I just want to know if there is a easier way to do it then from what I did in code below.

The next part is that I also want to make sure the user doesn't type in letters. like "gfgfadggdagdsg" for a choice.

Here is my code of the part I am working on....

public void businessAccount()
    {


        int selection;

        System.out.println("\nATM main menu:");
        System.out.println("1 - View account balance");
        System.out.println("2 - Withdraw funds");
        System.out.println("3 - Add funds");
        System.out.println("4 - Back to Account Menu");
        System.out.println("5 - Terminate transaction");
        System.out.print("Choice: ");
        selection = input.nextInt();

            if (selection > 5){

            System.out.println("Invalid choice.");
            businessAccount();

        }
            else if (selection < 1){
                System.out.println("Invalid choice.");
                businessAccount();
            }
            else {

        switch(selection)
        {
        case 1:
            viewAccountInfo3();
            break;
        case 2:
            withdraw3();
            break;
        case 3:
            addFunds3();
            break;
        case 4:
            AccountMain.selectAccount();
            break;
        case 5:
            System.out.println("Thank you for using this ATM!!! goodbye");
        }
            }
    }
3
  • this code is OK. you could skip checking < 1 and > 5 by putting a default case that prints invalid input Commented Sep 27, 2012 at 4:39
  • Be careful with recursion, you can get yourself in trouble and end up with some weird errors if you are not used to using it. For example, in your code when you call businessAccount from within businessAccount, if any code existed outside your else statement, it would run multiple times and the last time it would run won't be the time you are expecting it to. Right now you are ok, but if you edit this method in the future you could get unexpected behavior. Commented Sep 27, 2012 at 4:40
  • 1
    I would also recommend adding 'default' to the bottom of your switch statement to print an error message. Commented Sep 27, 2012 at 4:42

4 Answers 4

7

You may get rid of checking < 1 and > 5 by adding a default case.

try{
     selection = input.nextInt();        
     switch(selection){
      case 1:
          viewAccountInfo3();
          break;
      case 2:
          withdraw3();
          break;
      case 3:
          addFunds3();
          break;
      case 4:
          AccountMain.selectAccount();
          break;
      case 5:
          System.out.println("Thank you for using this ATM!!! goodbye");
          break;
      default:             
          System.out.println("Invalid choice.");
          businessAccount();

      }
}catch(InputMismatchException e){
    //do whatever you wanted to do in case input is not an int
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply, also how would I check to make sure the user enters numbers and not characters?
refer this catch InputMismatchException and then show error message.
0

Using BufferedReader you can do something like this:

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
int selection = 0;

try{
    selection = Integer.parseInt(s);
    if(selection > 5 || selection < 1){
        System.out.println("Invalid choice.");
        businessAccount();
    }else{
        // your switch code here
    }
    // you can use @Nishant's switch code here. it is obviously better: using switch's default case.
}catch(NumberFormatException ex){
    // throw new Exception("This is invalid input"); // or something like that..
    System.out.println("Invalid choice.");
    businessAccount();
}

Hope that helps.

Note: you must import java.lang.NumberFormatException import java.io.InputStreamReader and import java.io.BufferedReader

3 Comments

getting an error on br.readline(); saying unhandled IOEXCEPTION
You can add another catch(IOException ex){ } block after or before the current catch block
Not sure what you mean, still new to java
0

Use the switch case it's better and more speed the if statement when you check selection from a Specific.

Comments

-1

an alternative would to use regular expressions to get it work. Say you have a string x then

String x = "something";

if(x.matches("regex")){

}

Another way to do this is surround with try catch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.