We will check whether string is a number or not – with the help of logic we will solve this problem,
我们将检查字符串是否为数字-借助逻辑,我们将解决此问题,
In the first step, we will take a string variable named str and store any value in it.
第一步,我们将使用一个名为str的字符串变量,并将任何值存储在其中。
In the second step, We will take a boolean variable named str_numeric which stores Boolean value like true or false. Let us suppose that given string is numeric so that initially boolean variable str_numeric is set to true.
在第二步中,我们将使用一个名为str_numeric的布尔变量,该变量存储布尔值(如true或false) 。 让我们假设给定的字符串是数字,因此最初的布尔变量str_numeric设置为true。
In the third step we will do one thing in the try block we will convert String variable to Double by using parseDouble() method because initially we are assuming that given the string is number that's why we are converting first.
在第三步中,我们将在try块中做一件事,我们将使用parseDouble()方法将String变量转换为Double,因为最初我们假设给定的字符串是数字,这就是我们首先进行转换的原因。
If it throws an error (i.e. NumberFormatException), it means given String is not a number and then at the same time boolean variable str_numeric is set to false. Otherwise given string is a number.
如果抛出错误(即NumberFormatException ),则意味着给定的String不是数字,然后将布尔变量str_numeric设置为false 。 否则,给定的字符串是一个数字。
Example:
例:
public class IsStringNumeric {
public static void main(String[] args) {
// We have initialized a string variable with double values
String str1 = "1248.258";
// We have initialized a Boolean variable and
// initially we are assuming that string is a number
// so that the value is set to true
boolean str_numeric = true;
try {
// Here we are converting string to double
// and why we are taking double because
// it is a large data type in numbers and
// if we take integer then we can't work
// with double values because we can't covert
// double to int then, in that case,
// we will get an exception so that Boolean variable
// is set to false that means we will get wrong results.
Double num1 = Double.parseDouble(str1);
}
// Here it will raise an exception
// when given input string is not a number
// then the Boolean variable is set to false.
catch (NumberFormatException e) {
str_numeric = false;
}
// if will execute when given string is a number
if (str_numeric)
System.out.println(str1 + " is a number");
// Else will execute when given string is not a number
else
System.out.println(str1 + " is not a number");
}
}
Output
输出量
D:\Programs>javac IsStringNumeric.java
D:\Programs>java IsStringNumeric
1248.258 is a number
翻译自: https://www.includehelp.com/java/how-to-check-if-string-is-number-in-java.aspx