質問するログイン新規登録

回答編集履歴

1

ネストが深くなりすぎるのが嫌なので処理順変更

2016/11/11 05:02

投稿

swordone
swordone

スコア20675

answer CHANGED
@@ -1,6 +1,7 @@
1
1
  ややこしい仕様や設計はメイン処理に書かず、オブジェクトにまとめるようにします。
2
2
  具体的には、データの妥当性の判定(データ欠落、日にち間違いなど)はコンストラクタで、
3
3
  並び順はComparableを付けてcompateToで判定させます。
4
+ (以下コードは動作未検証)
4
5
  ###Readerクラス
5
6
  ```java
6
7
  import java.io.BufferedReader;
@@ -20,37 +21,35 @@
20
21
  List<Mysort> tmpList = new ArrayList<Mysort>();
21
22
  File file = new File(args[0]); // CSVデータファイル
22
23
 
23
- if (file.isFile()) {
24
+ if (!file.isFile()) {
25
+ System.out.println("ファイル指定が間違っています");
26
+ System.exit(-1);
27
+ }
24
- try (BufferedReader br = Files.newBufferedReader(Paths.get(args[0]), Charset.forName("MS932"))) {
28
+ try (BufferedReader br = Files.newBufferedReader(Paths.get(args[0]), Charset.forName("MS932"))) {
25
- // ファイルオープン
29
+ // ファイルオープン
26
- String line;
30
+ String line;
27
- final boolean acsend = br.readLine().equals("0");
31
+ final boolean acsend = br.readLine().equals("0");
28
- while ((line = br.readLine()) != null) {
32
+ while ((line = br.readLine()) != null) {
29
- try {
33
+ try {
30
- // ごちゃごちゃと判定を書く必要がなく、コードがスッキリする
31
- Mysort M = new Mysort(line);
34
+ Mysort M = new Mysort(line);
32
- tmpList.add(M);
35
+ tmpList.add(M);
33
- } catch (IllegalArgumentException e) {
36
+ } catch (IllegalArgumentException e) {
34
- e.printStackTrace();
37
+ e.printStackTrace();
35
- }
36
-
37
38
  }
38
- // 昇順、降順もこれで一発
39
- if (acsend) {
40
- Collections.sort(tmpList);
41
- } else {
42
- Collections.sort(tmpList, Collections.reverseOrder());
43
- }
44
39
 
45
- for (int i = 0; i < tmpList.size(); i++) {
46
- System.out.println(tmpList.get(i));
47
- }
48
- } catch (IOException e) {
49
- e.printStackTrace();
50
40
  }
41
+
42
+ if (acsend) {
43
+ Collections.sort(tmpList);
51
- } else {
44
+ } else {
45
+ Collections.sort(tmpList, Collections.reverseOrder());
46
+ }
47
+
48
+ for (int i = 0; i < tmpList.size(); i++) {
52
- System.out.println("ファイル指定が間違っています");
49
+ System.out.println(tmpList.get(i));
50
+ }
51
+ } catch (IOException e) {
53
- System.exit(-1);
52
+ e.printStackTrace();
54
53
  }
55
54
  }
56
55