notsavv
notsavv

Reputation: 21

Is there a better way to check if the user entered a number between 1-50?

It's been a few days since I started learning Java and currently I'm messing around with what I've learned so far. In this method, Im trying to make sure that the user inputs a number between [1 - 50].

The way I did it seems a bit odd to say the least,
so I'd appreciate some feedback from experienced programmers.

public static int humanNumber()
{

    Scanner sc = new Scanner (System.in);
    System.out.println ("enter a number between 1 and 50.");
    int x = sc.nextInt();

        if ( x < 1 || x > 50)
        {
          do
          {
            System.out.println ("enter A number between 1 and 50!!");
            x = sc.nextInt();
          } while (x<1 || x>50);
        }


    return x;
}

Upvotes: 0

Views: 91

Answers (3)

Bohemian
Bohemian

Reputation: 425053

Yes: Delete the repeated code outside the loop:

Scanner sc = new Scanner (System.in);
int x;
do {
    System.out.println ("enter A number between 1 and 50!!");
    x = sc.nextInt();
} while (x<1 || x>50);
return x;

Upvotes: 2

Veselin Davidov
Veselin Davidov

Reputation: 7081

I think your way looks fine - it works :) Another way would be to do:

 public static int humanNumber() {
     Scanner sc = new Scanner (System.in);
     int x = 0;
     while(x<1 || x>50) {
           System.out.println ("enter A number between 1 and 50!!");
            x = sc.nextInt();
     }
     return x;
}

The advantage is one less repeat of the system out and the sc.nextInt()

Upvotes: 2

Mureinik
Mureinik

Reputation: 311428

Instead of an if and a do-while loop, you could use a while loop:

while (x < 1 || x > 50) {
    System.out.println ("Enter a number between 1 and 50!");
    x = sc.nextInt();
}

Upvotes: 2

Related Questions