Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 只是字符串中的数字_Java_String_Double - Fatal编程技术网

Java 只是字符串中的数字

Java 只是字符串中的数字,java,string,double,Java,String,Double,我有随机生成的字符串(例如138fj*28+/dg) 如何测试给定字符串是否仅由数字组成。比如说, if(str="247339") true; else if(str="a245") false; 尝试使用Pattern类的matches方法 boolean b = Pattern.matches("\\d+", "138fj*28+/dg"); if(b) //number else // not a number 您可以在字符串中使用matches方

我有随机生成的字符串(例如
138fj*28+/dg

如何测试给定字符串是否仅由数字组成。比如说,

if(str="247339")
    true; 
else if(str="a245")
    false; 

尝试使用Pattern类的matches方法

boolean b = Pattern.matches("\\d+", "138fj*28+/dg");
 if(b)
   //number
 else
   // not a number

您可以在字符串中使用matches方法。 e、 g

输出:

Only integer   23343453 :true
With character 2334a3453 :false
With symbols   2*33434/53 :false
Only integer   23343453 :true
With character 2334a3453 :false
With symbols   2*33434/53 :false

您有两个选项,一个是使用正则表达式,另一个是解析字符串

以下是正则表达式方法:

public class Main {

    public static void main(String[]args) {
        Pattern pattern = Pattern.compile("^[0-9]*$");
        Matcher matcher = pattern.matcher("138fj*28+/dg");

        if (matcher.matches()) {
            System.out.println(true);
            // number
        }else {
            System.out.println(false);
            // not
        }
    }
}
输出为:false

以下是解析方法:

public class Main {

    public static void main(String[]args) {

        try {
            double number = Double.parseDouble("138fj*28+/dg");
            System.out.println(true);
            // number
        }catch (NumberFormatException ex) {
            System.out.println(false);
            // not
        }

    }
}

输出为:false

查看正则表达式模式和匹配器
public class Main {

    public static void main(String[]args) {

        try {
            double number = Double.parseDouble("138fj*28+/dg");
            System.out.println(true);
            // number
        }catch (NumberFormatException ex) {
            System.out.println(false);
            // not
        }

    }
}