dimanche 25 septembre 2016

Take input form keyboard and see if it matches format

I am trying to write a program that take user input from the keyboard and is called year. If the input equals a 4 digit year, output the year. If the input equals 2 digits add it to 2000 and output that. I wanted to use a switch statement but still confused on how to format it correctly. I decided to go with a If/else statement for my own sake. Any help would be greatly appreciated! Thank you!

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    final String FULL_YEAR = "[0-9]{4}";
    final String TWO_YEAR ="[0-9]{2}";
    System.out.println("Please enter a year");
    String Year = scan.next();

    if (Year.matches(FULL_YEAR))
    {
        System.out.println("The year is " + Year);
    }
        else
    {
        System.out.println("Invalid Year");
    }

    if (Year.matches(TWO_YEAR))
    {
        System.out.println("The year is " + 2000+Year);
    }
}

Aucun commentaire:

Enregistrer un commentaire