您的位置:首页 > 编程语言 > Java开发

JAVA 中两种判断输入的是否是数字的方法

2015-06-11 11:26 776 查看
注意要引入包 java.util.regex

用于匹配字符序列与正则表达式指定模式的类。

import java.io.*;
import java.util.regex.*;

public class isInteger {

public static void main(String[] args) {

try {
System.out.println("请输入第一个数字:");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String num1 = reader.readLine();
while (!num1.matches("\\d+")) {
System.out.println("输入的不是数字,请重新输入");
num1 = reader.readLine();
}
System.out.println("请输入第二个数字:");
String num2 = reader.readLine();
while (!Pattern.compile("[0-9]*").matcher(num2).matches()) {
System.out.println("输入的不是数字,请重新输入");
num2 = reader.readLine();
}
int result = Integer.parseInt(num1) * Integer.parseInt(num2);
System.out.println("乘积是:" + result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: