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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM