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