-3
int ID;

Scanner scan = new Scanner(System.in);
ID = Integer.parseInt(scan.nextLine());

do{
   System.out.println("Improper EMPID, please reenter your EMPID.\n");
   Scanner scan1 = new Scanner(System.in);
   ID = Integer.parseInt(scan1.nextLine());
}
while (ID > 999999 && ID < 10000000);

return ID;

This is a function in my main code where I attempt to have the user enter a seven digit ID.
It's supposed to loop infinitely until the user enters seven digits, however will only loop through once then exits.

I have also done this with a while loop with the same results. Something I'm not seeing here?

  Scanner scan = new Scanner(System.in);
  int id = Integer.parseInt(scan.nextLine());

  while (id >= 10000000 || id <= 999999);{
     System.out.println("Please enter your EMPID\n");
     id = Integer.parseInt(scan.nextLine());
  }


  return id;

My code now looks like this.

It will constantly loop without showing the print.

  • 2
    You are checking the values in the loop condition, not the amount of digits! The loop never gets entered because there is no number (-value) between 999999 and 1000000 that can be stored as `int` or `Integer`. Have a look at [this question about the amount of digits of an `int`](https://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int). You can check the value, but then only check if it is less than 10000000 to make it less than 7 digits. – deHaar Aug 30 '18 at 14:30
  • 2
    And you don’t need a new scanner each time – Joakim Danielson Aug 30 '18 at 14:32
  • deHaar, how would I be able to do that? Also I just realized it wont work as a do-while loop, so I have changed it back to a while loop – Christopher Roskind Aug 30 '18 at 14:32

3 Answers3

4

You should continue the loop when the input is invalid:

while (ID <= 999999 || ID >= 10000000);

Not related to the question, but please name variables with camel case, and remove unecessary code:

Scanner scan = new Scanner(System.in);
int id = Integer.parseInt(scan.nextLine());

while (id <= 999999 || id >= 10000000) {
    System.out.println("Improper EMPID, please reenter your EMPID.\n");
    id = Integer.parseInt(scan.nextLine());
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
0

You don't check the lenght of the input, you check for the real value. You can use int length = String.valueOf(ID).lenght(); to get the lenght of an int value.
Just a hint: Don't create new scanners each time, you will confuse your self. One is just fine.

ItFreak
  • 2,299
  • 5
  • 21
  • 45
0

this logic would be better with a while loop since you first ask the user for a value and want to give them an error message only if it's wrong

such as

 Scanner scan = new Scanner(System.in);
 int ID = Integer.parseInt(scan.nextLine());
 while (!ID || ID <= 999999 || ID >= 10000000) {
    System.out.println("Improper EMPID, please reenter your EMPID.\n");
    ID = Integer.parseInt(scan1.nextLine());
}