1. 無限ループ内に1,2,3,...を出力させ、このループを特定のキー入力で止める。

せっかくはてなのメンバーなのに、全く活用していなかったので、使ってみることにします。

動機はこれ。
Think Different. – A dream does not escape. but I always escapes.


とりあえず作ってみようということでひとつめ。
まずは手慣れているはずの Java で作ってみました。
目指すは http://www.kernelthread.com/hanoi/ で紹介されている言語の制覇。
キー入力を受けつけない言語もあるので、今回やった 1 のようなやつは、割愛しようということで。。

1. 無限ループ内に1,2,3,...を出力させ、このループを特定のキー入力で止める。

/**
 * $Id: Example1.java 1163 2007-03-10 10:38:04Z nanasess $
 */
package jp.examples;

import java.io.IOException;

/**
 * Example1
 * 
 * <pre>
 * 1. Display series of numbers (1,2,3,4, 5....etc) in an infinite loop. 
 *    The program should quit if someone hits a specific key (Say ESCAPE key).
 * </pre>
 *
 * @author $Author: nanasess $
 * @version $Revision: 1163 $ $Date: 2007-03-10 19:38:04 +0900 (土, 10 3 2007) $
 */
public class Example1 {

    /** Escape key のキーコード. */
    private static final int ESC_CODE = 27;
    
    /**
     * ESC キーを押すまで, 引数の回数分ループさせループ数を出力する.
     *
     * @param args ループ回数
     * @throws IOException 入力例外が発生した場合
     * @see http://d.hatena.ne.jp/kajidai/20061025/1161711473
     * @see http://forums.programming-designs.com/viewtopic.php?pid=3482
     */
    public static void main(String[] args) throws IOException {
        
        if (args == null) {
            throw new IllegalArgumentException("Prease input argument.");
        }
        if (args.length != 1) {
            throw new IllegalArgumentException("Input argument of requied once.");
        }
        int count = 0;
        try {
            count = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Input argument of number.");
        }
        int i = 0;
        while(i < count) {
            int c = System.in.read();
            if (c == ESC_CODE) break;
            System.out.println(i);
            i++;
        }
    }
}

ループ回数は引数で指定できるようにしました。
また、 Java の場合は System.in.read() で入力待ちの状態になってしまうので、 Enter キーをクリックしないと先へ進みません。
Swing とか使えば、例題のようなことが完璧に実現可能かもしれませんが、詳細は調べておりません。。
普段は Webアプリばかり書いているので少々手間どってしまいました(汗)

でも基本は大切ですもんねえ。