您可以检查给定的字符串是否为数字,如以下程序所示。
import java.util.Scanner; public class StringNumeric { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a string ::"); String str = sc.next(); boolean number = str.matches("-?\\d+(\\.\\d+)?"); if(number) { System.out.println("Given string is a number"); } else { System.out.println("Given string is not a number"); } } }
输出结果
Enter a string :: 4245 Given string is a number