方法一正则表达式判断输入的数字是不是整数,并重新输入

1 /**
2 *
3 * 功能描述: 正则表达式判断输入的数字是不是整数,并重新输入
4 *
5 *
6 * @Author: apple.
7 * @Date: 2019/11/22 2:15 PM
8 */
9 public static void main(String[] args) {
10 Scanner sc = new Scanner(System.in);
11 String str = sc.next();
12 while (!(str.matches("^[1-9]\\d*$"))) {
13 System.out.println("输入的" + str + "不是整数,请重新输入");
14 str = sc.next();
15 }
16 System.out.println("输入的" + str + "是整数");
17 }
方法二 hasNextInt()方法判断输入是否为整数(较便捷)

1 /**
2 *
3 * 功能描述:
4 *
5 *
6 * @Author: apple.hasNextInt()方法判断输入是否为数字
7 * @Date: 2019/11/22 2:07 PM
8 */
9 public static void main(String[] args) {
10 Scanner sc = new Scanner(System.in);
11 System.out.println("请输入一个整数");
12 while(!sc.hasNextInt()){
13 System.out.println("输入的不是整数,重新输入:");
14 sc.next();
15 }
16 int num = sc.nextInt();
17 System.out.println("输出整数:"+num);
18 }
hasNextInt()方法说明参考:https://blog.csdn.net/qq_42609863/article/details/87085939
