- 追加された行はこのように表示されます。
- 削除された行は
このように表示されます。
{{category JAVA}}
{{category Java}}
{{category プログラミング}}
対話式のユーザインターフェースのためのJavaソースを生成するスクリプト
{{ref makeprompt.rb}}
下記に従って,コマンド名,コマンドの説明,実行部分を書いておくと,
それぞれのコマンドを実行する分岐と,helpコマンドを自動生成します.
コマンドプロンプトは
public void exec() throws IOException
として出力されます.
@PACKAGE パッケージ名
@PROMPT "プロンプト記号"
@COMMAND "コマンド名" "説明"
コマンドの本文
@IMPORT インポートパッケージ
@CATCH 例外クラス
例外をキャッチしたときの処理
@END
その後の記述をそのままJavaソースとして出力します
たとえば,Test.promptという名前の(拡張子は何でもいいけど),下記のようなデータから
@PROMPT "> "
@IMPORT java.io.File
@COMMAND "quit" "quit this program"
break;
@COMMAND "ls" "print file list in current directory"
File dir = new File(".");
String[] files = dir.list();
for(int i = 0; i < files.length; i++){
System.out.println(files[i]);
}
@CATCH Exception
System.out.println(e);
@END
public static void main(String[] args){
try{
Test.exec();
}catch(IOException e){
e.printStackTrace();
}
}
こんな感じのJavaソースを生成してくれます.
//
// generated by makeprompt.rb
//
import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.File;
public class Test{
private static void printUsage(String args){
System.out.println("usage: " + args);
}
private static String[] parseInput(String line) throws IOException{
String[] cmd = null;
StringTokenizer st = new StringTokenizer(line, " ");
cmd = new String[st.countTokens()];
for(int i = 0; i < cmd.length; i++) cmd[i] = st.nextToken();
return cmd;
}
public static void exec() throws IOException{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String line = "";
String cmd[] = null;
System.out.print("> ");
while((line = buf.readLine()) != null){
cmd = parseInput(line);
try{
if(cmd.length == 0 || cmd == null){
}else if(cmd[0].equals("quit")){
break;
}else if(cmd[0].equals("ls")){
File dir = new File(".");
String[] files = dir.list();
for(int i = 0; i < files.length; i++){
System.out.println(files[i]);
}
}else if(cmd[0].equals("help")){
System.out.println("quit quit this program");
System.out.println("ls print file list in current directory");
}else{
printUsage("unknwon command: " + cmd[0]);
}
}catch(Exception e){
System.out.println(e);
}finally{
System.out.print("> ");
}
}
}
public static void main(String[] args){
try{
Test.exec();
}catch(IOException e){
e.printStackTrace();
}
}}