解答例 - 実習課題3 - 3.その他の入出力クラス
(実習課題3)
以下のプログラムを作成しなさい。
- キーボードから複数の数字を読み取り、その数字をソーティングした結果をコンソールに表示するプログラム。
解答例
/**
* StandardInputExample.java
* TECHSCORE Java 入出力3章 実習課題3
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.io.chapter3.exercise3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class StandardInputExample {
public static void main(String[] args) {
try {
System.out.println("並び替える数字を入力してください");
System.out.println("終わるときは単にエンターを押してください");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
ArrayList list = new ArrayList();
while (true) {
line = reader.readLine();
if ("".equals(line)) {
break;
}
//読み込んだ値をリストに追加
list.add(Integer.valueOf(line));
}
//リストをソートする
Collections.sort(list);
System.out.println("ソート後");
for (int i = 0; i < list.size(); i++) {
System.out.println((Integer)list.get(i));
}
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
} catch (NumberFormatException e) {
System.out.println("半角数字で入力してください");
e.printStackTrace();
System.exit(0);
}
}
}

