package Game;

import java.util.Scanner;

public class Zzz {
    
    public static void main(String[] args) {
        System.out.println("请输入一个数字:");
        Scanner sc= new Scanner(System.in);
        int num = 0;
        while(!sc.hasNextInt()) {
            sc.next();
        }
        num = sc.nextInt();
        System.out.println("数字为:"+num);
    }

}

 

hasNextInt方法的使用

 

值得注意的是,不管是连续输入多个整数还是连续输入直到输入了整数,while循环中都需要执行next这类函数。这是因为hasNextInt只是判断输入流中下一个输入是否是整数,如果把next这类函数去掉,那么输入流根本不会变化,hasNextInt的判断结果总是一样,这不小心就会导致死循环。

所以,hasNextInt要结合next,nextInt等方法一起使用

参考:

 

https://jingyan.baidu.com/article/5552ef4784fdac518efbc947.html

相关文章:

  • 2022-01-02
  • 2022-12-23
  • 2021-07-18
  • 2021-12-18
  • 2022-01-21
  • 2021-07-30
  • 2021-10-22
  • 2021-11-09
猜你喜欢
  • 2021-12-26
  • 2021-06-16
  • 2021-10-21
  • 2021-06-27
  • 2021-10-03
  • 2022-02-18
  • 2021-11-08
相关资源
相似解决方案