2

我是 Java 编程新手。

我想system.out.println记录用户输入的日期,并让它知道它是否是“st”、“th”、“rd”和“nd”。因此,如果我输入“13”作为我的出生日期,它会添加“th”以使其成为“13th”。

如何使用所有数字“1”到“31”自动执行此操作?

我应该使用并行数组,并且有一部分是 '1' 到 '31' [0] - [30],一部分是 [0] - [3] 用于 st,nd,rd,th?并让它们相应地匹配?

如果是这样或不是,我该如何声明它等等?

对不起,写得很糟糕的问题。我很难说出我的想法。

4

5 回答 5

1
public static void main(String[] args) {
        String[] dates = {"","1st","2nd","3rd","4th",...,"31st"};
        int input = 24;
        System.out.println(dates[input]);
}
于 2013-02-03T01:05:13.650 回答
1

我宁愿那样做:

String getExtension(int day) {

  switch(day) {

    case 1:
    case 21:
    case 31:
    return "st";

    case 2:
    case 22:
    return "nd";

    case 3:
    case 23:
    return "rd";

    default:
    return "th";
  }

}


String formatDay(int day) {
   return day + getExtension(day);
}
于 2013-02-03T01:07:47.727 回答
0

我不认为你需要这样做。关于日期的这种附属物有明确定义的规则。

  • 如果日期以 1 结尾且小于 10 或大于 20,则以 'st' 结尾。
  • 如果日期以 2 结尾且小于 10 或大于 20,则以 'nd' 结尾。
  • 如果日期以 3 结尾且小于 10 或大于 20,则以 'rd' 结尾。
  • 所有其他日期以“th”结尾。

这是我设计过度的解决方案。从它那里得到你想要的。

public String appendDateEnding(String theDate) {
    if(null != theDate) {
        try {
            return appendDateEnding(Integer.parseInt(theDate));
        } catch (NumberFormatException e) {
            // we'll return null since we don't have a valid date.
        }
    }
    return null;
}

private String appendDateEnding(int theDate) {
    StringBuffer result = new StringBuffer();
    if(32 <= theDate || 0 >= theDate) {
        throw new IllegalArgumentException("Invalid date.");
    } else {
        result.append(theDate);
        int end = theDate % 10;
        if(1 == end && isValidForSuffix(theDate)) {
            result.append("st");
        } else if(2 == end && isValidForSuffix(theDate)) {
            result.append("nd");
        } else if(3 == end && isValidForSuffix(theDate)) {
            result.append("rd");
        } else {
            result.append("th");
        }
    }
    return result.toString();
}

private boolean isValidForSuffix(int theDate) {
    return (10 > theDate || 20 < theDate);
}

如果给定 1 到 31 之间的天数,它会打印什么:

1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
26th
27th
28th
29th
30th
31st
于 2013-02-03T01:26:55.447 回答
0

我会使用 switch 语句

 int day;
    // no read in or assign day: 1 - 31

String ext;
// day % 10 (modulo 10) reduces to 0-9
switch (day % 10) {
case 1: ext = "st"; 
  break;
case 2: ext = "nd"; 
  break;
case 3: ext = "rd"; 
  break;
default: ext = "th";
  break;
}
if (day >= 11 && day <==13) ext == "th";
String dayText = "day: " + day + ext;
于 2013-02-03T01:02:07.947 回答
0

我建议使用 switch 语句,但确保命令它包含 11、12 和 13。

switch (day) {
case 2:
case 22:
    suffix = "nd";
    break;
case 3:
case 23:
    suffix = "rd";
    break;
default:
    //Accounts for all other numbers including 1, 11, 12, 13, 21, and 31
    suffix = "st";
    break; //Because I'm a conformist.
}
于 2013-02-03T01:12:00.483 回答