- PR -

javaにおいて

1
投稿者投稿内容
sarusaru
会議室デビュー日: 2004/03/19
投稿数: 14
投稿日時: 2004-04-30 13:55
現在、エクリプスを使用しjavaを勉強してるのですが、int型入力しないといけないところにstring型を入力した時にエラーとなるので、再度入力してくださいと表示させた後に再度入力できるようにするにはどのようにしたらよいでしょうか?
OSはwindows xpです。
taku
ぬし
会議室デビュー日: 2002/11/12
投稿数: 918
お住まい・勤務地: 墨田区→中野区
投稿日時: 2004-04-30 14:26
 こんなのでしょうか?

コード:

//サンプル
import java.io.*;

public class Sample{

static public void main(String args[]){
try{
if(args.length==0) throw new NumberFormatException();
else Integer.parseInt(args[0]);
}catch(NumberFormatException e){
System.out.println("数字を入力してください");
try{
args = new String[]{new BufferedReader(new InputStreamReader(System.in)).readLine()};
}catch(IOException ie){
ie.printStackTrace();
}
}
System.out.println("入力値="+args[0]);
}

}



[ メッセージ編集済み 編集者: taku 編集日時 2004-04-30 14:27 ]
でゅうく
大ベテラン
会議室デビュー日: 2003/11/30
投稿数: 129
投稿日時: 2004-04-30 15:35
再入力の機能が必要なんですよね?
コード:
BufferedReader reader =
	new BufferedReader(new InputStreamReader(System.in));
boolean complete = false;
int inputNumber = 0;
while (!complete) {
	String input = null;
	try {
		System.out.print("数字を入力してください:");
		input = reader.readLine();
		inputNumber = Integer.parseInt(input);
		complete = true;
	} catch (NumberFormatException ignore) {
		System.out.println("入力に誤りがあります。:" + input);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
System.out.println("有効な入力:" + inputNumber);

Wata
ぬし
会議室デビュー日: 2003/05/17
投稿数: 279
投稿日時: 2004-04-30 15:44
あの〜
まず、コマンドラインアプリケーションなのか、GUIアプリケーションなのか、
Webアプリケーションなのかをはっきりさせておかないと、徒労に終わる可能性が
高いと思うのですが…
1

スキルアップ/キャリアアップ(JOB@IT)