Xzavier
Xzavier

Reputation: 53

Turning a number input into a year

My goal for this program is to ask the user for the year by entering an integer. For example, if the user inputs "05" or "87" or "2017", the output would be "2005" or "2087" or just "2017". The program is only meant account for 2 and 4 spaces in the input. If the user were to input "123" for example, the output would be "123 is an invalid year or "12345" the output would be "12345 is not a year. I am having trouble with the case in my code and do not know how to correct it.

import java.util.Scanner;

public class Y2k
{
  public static void main( String [ ] args )
  {
    Scanner scan = new Scanner ( System.in );

    // establish string and number to be apply to input
    String year;
    int sand = 20;

    // ask for the year 
    System.out.println( "Enter a year: " );
    year = scan.next( );
    char ohTwo = year.charAt( 1 );

    // perform the year and print the result
    switch ( year )
    {
      case "05": 
        System.out.println( sand + year ); //output year and input
        break;
    }
  }
}

For any assistance with this matter, thank you in advance.

Upvotes: 2

Views: 106

Answers (2)

jonasfh
jonasfh

Reputation: 4579

To actually implement this using a switch-statement, do something like:

import java.util.Scanner;

public class Y2k
{
  public static void main(String [] args)
  {
    Scanner scan = new Scanner (System.in);

    // establish string and number to be apply to input
    String year;
    int sand = 20;

    // ask for the year 
    System.out.println("Enter a year: ");
    year = scan.next();

    try {
      System.out.println(getYear(year)); //output year and input
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }

  public String getYear(String input) {
    String sand = "20"
    // Typically also check that input is in fact an integer, in a sane range, etc.
    switch (input.length()) {
      case 2: 
        return sand + input;
      case 4: 
        return input;
      default:
        throw new RuntimeException(input + " is an invalid year.");
    }
  }
}

Upvotes: 0

Fernando Bravo Diaz
Fernando Bravo Diaz

Reputation: 579

Do this instead of the if else statement if you wanna use switch:

    switch(year.length()){
            case 2:
                System.out.println(sand + year);
            break;
            case 4:
                System.out.println(year);
            break;
            default:
                System.out.println(year+" is an invalid year.");
            break;
        }

Upvotes: 2

Related Questions