dポイントプレゼントキャンペーン実施中!

キーボードから入力した文字列が数字かどうかを判別したいのです。
入力した文字列が数字ではない間、またその逆の文字列が数字の間ループさせたいのです。
ループさせないやり方(Integer.parseInt(String)で数字でなければcatchで処理する)はわかるのですが・・・

import java.io.*;

class Test{
public static void main(String[] args){
String str = "";

BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));

try{
do {
str = br.readLine();
System.out.print("\n");
}while(strが数字の間、もしくは数字以外の間)
}
catch(Exception e){
System.err.println(e);
}
}
}

上のプログラムのwhileの中で判別したいのです。
よろしくお願いします。

A 回答 (2件)

str.matches("-?\d+");



とか?
    • good
    • 0
この回答へのお礼

str.matches("-?\\d+");
でやるとうまくいきましたありがとうございます。

お礼日時:2008/10/09 16:23

import java.io.*;



//たとえば…

class Test{
public static void main(String[] args){
String str = "";

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

try{
boolean isNumeric = false;
do {

str = br.readLine();
try{
isNumeric = true;
Integer.parseInt(str);

}catch(NumberFormatException e){
isNumeric = false;
}

}while(isNumeric == false);
}catch(Exception e){
System.err.println(e);
}
}
}
    • good
    • 0
この回答へのお礼

あっそういうやり方もあるんですね・・・
参考になりました。ありがとうございました。

お礼日時:2008/10/09 16:24

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!