hasNextInt方法的使用

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);
    }

}

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

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

参考:

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

猜你喜欢

转载自www.cnblogs.com/hxtzzz/p/11242877.html
今日推荐