0

I'm trying to make it so it shows an error message if a user uses more or less than 4 digits.

Code snippet

int pin = scan.nextInt(); // Read user input
    if (pin > 4 && pin < 4) {
        System.out.println("Invalid Usage, please try again ");
    }
    if (pin == 9681){
        System.out.println("Correct Pin");
    } else {
        System.out.println("Incorrect Pin, please try again.");

I know that it's not counting the digits but I have no idea what other function I should use.

Techout
  • 11
  • 3
  • 6
    Two solutions I see would be to either compare pin to 1000 and 9999 instead of 4, or to convert pin to a string and get its length. Also, you likely want to use an `or` operator rather than `and`, as pin cannot be both less than 4 and simultaneously greater than 4. – SelflessPotato Dec 12 '21 at 18:43
  • 2
    No number is ever larger than 4 and smaller than 4 at the same time. Should use `||` instead of `&&`. – luk2302 Dec 12 '21 at 18:44
  • 1
    In your own words, what is the smallest positive integer that has 4 digits? What is the biggest positive integer that has 4 digits? Are there any positive integers in between with a different number of digits? Knowing this, can you think of a way to solve the problem? – Karl Knechtel Dec 12 '21 at 18:51

1 Answers1

1

We need to show an error message if a user is using more than 4 digits. So our 4 digit number starts from 1000 and stops at 9999. Any number that are less than 1000 or any number that are greater than 9999 is against the rule and at that condition we can show the error message else we can show its valid pin.

int pin = sc.nextInt();
if (pin < 1000 || pin > 9999) {
    System.out.println("The error message that pin must be 4 digit");
}
else {
    System.out.println("Valid Pin");
}

This works when you are inputing in the form of an integer, if you are taking a string as input, then just checking the length of the string will do the job.

// in case of string as input
String pin = sc.next();
if (pin.length() < 4 || pin.length() > 4) {
    System.out.println("The error message");
}
else {
    System.out.println("Valid pin");
}
Rohith V
  • 1,089
  • 1
  • 9
  • 23