1

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:

System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();

Any help would be greatly appreciated.

1
  • 1. Use an array or ArrayList to hold your numbers. 2. Use a for loop to get the numbers. 3. Yes sure go ahead and try to validate the input with an if block, but please show us your attempt to do it with your question. Else we won't know what you might be doing wrong, or what assumptions you have might be wrong. You may even surprise yourself and come up with a solution -- something that would be the best possible outcome for this question. Commented Sep 14, 2015 at 20:40

4 Answers 4

1

You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.

Replace val with your actual variable names.

if (val < 0 || val > 19) {
    System.out.println("please read the instructions again");
    System.exit(0);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Isn't a system exit a little harsh there?
@DarkSquirtings it's what OP asked for, but yes
@DarkSquirtings would you mind telling me why it's considered harsh? It was on the exercise that I'm trying to do so I just assumed it's the usual way to quit the program.
First, you're making the user re-launch the program instead of just giving him another shot at giving you correct input. Second, you generally want your program to exit through a predictable path. Ideally, there should be one exit point for your program. There might be a lot of things that need cleaning up in a complex program, such as a connection to a database or things that need to be saved to a file. What you should do (in the event that the program really does need to exit) is throw an exception, and let it percolate up to a higher-level class that knows how to end the program gracefully.
1

First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.

Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:

if (userNum < 0 || userNum > 19) {
    // print error message, and quit here
}

Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:

boolean runApplication = true;

while(runApplication) {
    // do your for-loop with user input scanning
}

Then set the runApplication flag as needed based on whether or not the user put in valid numbers.

Comments

1

This code will do the trick for you, i added some securities :

public static void main(String[] args) {
    int count = 1;
    Scanner scan = new Scanner(System.in);
    List<Integer> myNumbers = new ArrayList<Integer>();
    System.out.println("Please enter 5 numbers between 0 and 19");
    do {
        System.out.println("Enter Number "+count+" ");
        if(scan.hasNextInt()){
            int input = scan.nextInt();
            if(input >= 0 && input <= 19){
                myNumbers.add(input);
                count++;
            }else{
                System.out.println("Please read instructions again");
                System.exit(0);
            }
        }else{
            scan.nextLine();
            System.out.println("Enter a valid Integer value");
        }
    }while(count < 6);

    /* NUMBERS */
    System.out.println("\n/** MY NUMBERS **/\n");
    for (Integer myNumber : myNumbers) {
        System.out.println(myNumber);
    }
}

Hope it helps

Comments

0

Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.

To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.

    System.out.println("Please enter a number between 0 and 19");
    Scanner scan = new Scanner(System.in);
    for(int i = 1; i <=5; i++){
    if(i == 1)
        System.out.println("1st Number");
    else if(i == 2)
        System.out.println("2nd Number");
    else if(i == 3)
        System.out.println("3rd Number");
    else
        System.out.println(i + "th Number");
    int numEntry = scan.nextInt();
    if(numEntry < 0 || numEntry > 19){
        System.out.println("Please read instructions again.");
        System.exit(1);
    }

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.