Java Character クラスを使って文字列が数値であるかどうかを調べるサンプル

環境
JavaSE-17
Eclipse 4.24.0 M2

書式
public static boolean isDigit(char ch)
指定された文字が数字かどうかを判定します。
Character.getType(ch)により示される汎用カテゴリ型がDECIMAL_DIGIT_NUMBERの場合、文字は数字になります。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class ArkgameTest {
public static void main(String[] args) {
String str = "456";
String strB = "a123";
boolean res = funA(str);
System.out.println(res);
boolean res2 = funA(strB);
System.out.println(res2);
}
/**
* 文字列が数値であるかどうか
*
* @param str 文字列
* @return true/falseを返す
*/
public static boolean funA(String str) {
boolean result = true;
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
result = false;
}
}
return result;
}
}
package com.arkgame.study; public class ArkgameTest { public static void main(String[] args) { String str = "456"; String strB = "a123"; boolean res = funA(str); System.out.println(res); boolean res2 = funA(strB); System.out.println(res2); } /** * 文字列が数値であるかどうか * * @param str 文字列 * @return true/falseを返す */ public static boolean funA(String str) { boolean result = true; for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { result = false; } } return result; } }
package com.arkgame.study;

public class ArkgameTest {

      public static void main(String[] args) {

            String str = "456";
            String strB = "a123";
            boolean res = funA(str);
            System.out.println(res);

            boolean res2 = funA(strB);
            System.out.println(res2);

      }

      /**
       * 文字列が数値であるかどうか
       * 
       * @param str 文字列
       * @return true/falseを返す
       */
      public static boolean funA(String str) {
            boolean result = true;
            for (int i = 0; i < str.length(); i++) {
                  if (!Character.isDigit(str.charAt(i))) {
                        result = false;
                  }
            }
            return result;

      }
}

実行結果
true
false

Java

Posted by arkgame