编写通用函数来执行操作

时间:2013-12-16 12:34:04

标签: java

我试图制作用户将进入年份的逻辑(例如2102,2001,1992等),返回值将是

Range     | Return-value  
1600-1699 | 2  
1700-1799 | 5    
1800-1899 | 3  
1900-1999 | 1  
2000-2099 | 2  
2100-2199 | 5  
2200-2299 | 3  
2300-2399 | 1  
2400-2499 | 2  

系列将继续......

示例1:假设用户输入了1900-1999的1991年,程序将输出返回值= 1(从表中)。我想为此制定一个独立的逻辑。

示例2:如果用户输入2521(2500-2599范围),则根据系列(2,5,3,1)的输出值将为“5”。

我该如何做到这一点?

2 个答案:

答案 0 :(得分:0)

在c#中测试过,但也应该在java中使用 - 模数运算符(%)和泛型的解决方案 - 它适用于任何日期。 首先它除以100然后使用模运算符 - 因为你的密钥订单每400年定期一次,它也适用于1600-2500之外的其他日期。

private int getKeyOf(int year)
{
    switch (year / 100 % 4)
    {
        case 0:
            return 2;
        case 1:
            return 5;
        case 2:
            return 3;
        case 3:
            return 1;
    }
    return -1;
}

答案 1 :(得分:0)

通过将正整数除以100,您将获得2个第一位数字。然后,在Java中给出:

protected int getKeyOf(int year) {
    switch (year / 100) {
    case 16:
        return 2;
    case 17:
        return 5;
    case 18:
        return 3;
    case 19:
        return 1;
    default:
        return -1;
    }
}
相关问题