回答編集履歴
3
Date-Time API
test
CHANGED
@@ -29,3 +29,65 @@
|
|
29
29
|
|
30
30
|
|
31
31
|
```
|
32
|
+
|
33
|
+
---
|
34
|
+
|
35
|
+
|
36
|
+
|
37
|
+
ちなみに、Java8のDate-Time APIを使って書いた例がこうなります。
|
38
|
+
|
39
|
+
```java
|
40
|
+
|
41
|
+
import java.time.DateTimeException;
|
42
|
+
|
43
|
+
import java.time.LocalDate;
|
44
|
+
|
45
|
+
import java.time.format.DateTimeFormatter;
|
46
|
+
|
47
|
+
import java.util.InputMismatchException;
|
48
|
+
|
49
|
+
import java.util.Scanner;
|
50
|
+
|
51
|
+
|
52
|
+
|
53
|
+
public class InputCal2 {
|
54
|
+
|
55
|
+
|
56
|
+
|
57
|
+
public static void main(String[] args) {
|
58
|
+
|
59
|
+
try (Scanner s = new Scanner(System.in)){
|
60
|
+
|
61
|
+
System.out.print("年を入力:");
|
62
|
+
|
63
|
+
int year = s.nextInt();
|
64
|
+
|
65
|
+
System.out.print("月を入力:");
|
66
|
+
|
67
|
+
int month = s.nextInt();
|
68
|
+
|
69
|
+
System.out.print("日を入力:");
|
70
|
+
|
71
|
+
int dayOfMonth = s.nextInt();
|
72
|
+
|
73
|
+
LocalDate date = LocalDate.of(year, month, dayOfMonth);
|
74
|
+
|
75
|
+
System.out.println(date.format(DateTimeFormatter.ofPattern("yyyy年M月d日(E)")));
|
76
|
+
|
77
|
+
} catch (InputMismatchException e) { //s.nextInt()からの例外
|
78
|
+
|
79
|
+
System.out.println("数値ではない文字が入力されました");
|
80
|
+
|
81
|
+
} catch (DateTimeException e) { //LocalDate.of()からの例外
|
82
|
+
|
83
|
+
System.out.println("入力された数値に誤りがあります");
|
84
|
+
|
85
|
+
}
|
86
|
+
|
87
|
+
}
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
}
|
92
|
+
|
93
|
+
```
|
2
Stringということに今気づいた
test
CHANGED
@@ -2,7 +2,7 @@
|
|
2
2
|
|
3
3
|
```java
|
4
4
|
|
5
|
-
//年月日の入力後
|
5
|
+
//年月日の入力後、Integer.parseInt()などで数値に変換して(変数名はそのままになってしまっています)
|
6
6
|
|
7
7
|
Calendar calendar = Calendar.getInstance();
|
8
8
|
|
1
月フィールドでミス
test
CHANGED
@@ -10,7 +10,7 @@
|
|
10
10
|
|
11
11
|
calendar.set(Calendar.YEAR, year);
|
12
12
|
|
13
|
-
calendar.set(Calendar.MONTH, month);
|
13
|
+
calendar.set(Calendar.MONTH, month - 1); //月のフィールドは0始まりなので1引かなければいけない
|
14
14
|
|
15
15
|
calendar.set(Calendar.DATE, day);
|
16
16
|
|