数字のみで構成された文字列かどうかを確認するサンプルソースになります。
サンプルソース内のisNumが実際に数字文字で構成された文字列かどうかを確認している部分になります。
確認(チェック)する文字列は、コマンドラインの引数として渡します。
数字のみの文字列かどうかは、Integer.praseIntを使って、エラー(例外)が発生しない場合は、数値文字のみで構成された文字列としtrueを返却。
エラー(例外)が発生した場合は、falseを返却します。
class IsNumSample {
private boolean isNum(String s) {
boolean b = true;
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
b = false;
}
return b;
}
private void usage(String[] args) {
if (args.length < 1) {
System.err.println("Usage: IsNumSample num num num ...");
System.exit(1);
}
}
private void checkArguments(String[] args) {
for (int i = 0; i < args.length; i++) {
if (!isNum(args[i])) {
System.out.println(args[i] + ": is *not* number. (TT)");
} else {
System.out.println(args[i] + ": is number. (^^)");
}
}
}
public static void main(String[] args) {
IsNumSample me = new IsNumSample();
me.usage(args);
me.checkArguments(args);
}
}
サンプルソースをコンパイルし実行した結果を以下に記します。
$ javac IsNumSample.java
$ java IsNumSample Usage: IsNumSample num num num ...
$ java IsNumSample 1 a 2 b 1.1 1: is number. (^^) a: is *not* number. (TT) 2: is number. (^^) b: is *not* number. (TT) 1.1: is *not* number. (TT)
以上、数字文字のみで構成された文字列かどうかを確認するサンプルソースでした。