Search code examples
javacomputer-science

Why does my Validare Zip Code(boolean) program return false?


The instruction to the program is: Zip codes consist of 5 consecutive digits. Prompt the user for a five digit zip code as a String. Create a Java method called isValid and pass the String as a parameter to the method. In the method determine whether the input is a valid zip code. A valid zip code is as follows: Must only contain numbers (no non-digits allowed). Must not contain any spaces. Must not be greater than 5 digits in length. If the zip code is valid return true to the main method, else return false.

Everytime I put in a valid zip code it still says false

this is my code:

import java.util.Scanner;
public class Main
{
  public static void main (String[]args)
  {
    Scanner input = new Scanner (System.in);
      System.out.println ("Enter a zip code: ");
    String zipCode = input.nextLine ();

      System.out.println (isValid (zipCode));
  }
  public static boolean isValid (String zipCode)
  {
    boolean yes = false;
    int i = 0;
    for (i = 0; i < zipCode.length (); i++)
      {
    
    int digit = zipCode.charAt (i);
    //if only contains number
    if (digit > 48 && digit < 57)
      {
        System.out.println (digit);
      }
    else
      {
        return false;
      }

    int len = zipCode.length ();
    if (len == 4)
      {
        System.out.println (len);
      }
    else
      {
        return false;
      }

      }
    return yes;
  }
}

Solution

  • You should include both 0 and 9 , Hence, please change this line

    if (digit > 48 && digit < 57)
    

    to

    if (digit >= 48 && digit <= 57)
    

    On the other hand, the length of a zip should be 5 instead of 4, Hence, please change this line:

    if (len == 4)
    

    to

    if (len == 5)