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