将数字输入转换为一年

时间:2018-02-08 22:27:36

标签: java

我对此计划的目标是通过输入整数来询问用户年份。例如,如果用户输入“05”或“87”或“2017”,则输出将为“2005”或“2087”或仅为“2017”。该程序仅在输入中占2个和4个空格。例如,如果用户输入“123”,则输出将是“123是无效年份或”12345“输出将是”12345不是一年。我在我的代码中遇到问题并且不知道如何纠正它。

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;
    }
  }
}

对于此事的任何帮助,请提前感谢。

3 个答案:

答案 0 :(得分:2)

如果您想使用switch,请执行此操作而不是if else语句:

err = db.Find(bson.M{"name": name,"password" :Password}).One(&logedUser)

答案 1 :(得分:0)

这是使用“if”语句的程序实现:

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();

        if(year.length() == 2){
            System.out.println(sand + year);
        } 
        else if(year.length() == 4){
            System.out.println(year);
        }
        else{
            System.out.println(year+" is an invalid year.");
        }

    }
}

此解决方案使用“if”语句。您可以使用此作为指南,使用案例方法创建自己的代码。

答案 2 :(得分:0)

要使用switch语句实际实现此功能,请执行以下操作:

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.");
    }
  }
}