[英]Scanner skipping over user input
我正在嘗試下象棋游戲,並且用戶在某個時候輸入了一個與他們想移動的棋子有關的數字。 我之前有以下代碼的簡化版本,但最近我決定放置一個“ try”和“ catch”語句來捕獲InputMismatchException。 這是代碼:
int inputexception = 0;
do {
inputexception = 0;
try {
System.out.println("What piece would you like to move?");
pieceselectioninput = scan.nextInt();
} catch ( InputMismatchException e ){
inputexception = 1;
}
} while ( inputexception == 1 );
因此,一旦我運行了該程序,如果我輸入了一個非Int值,它就會一直重復着“您想移動哪一塊?” 一直顯示在屏幕上,直到我手動終止程序為止。
我究竟做錯了什么? 在添加“ try”和“ catch”短語之前,並不是這樣。
只要inputexception == 1
運行while循環,然后在InputMismatchException的catch塊中將inpuexception值設置為1。 這使得每次鍵入非整數值時循環都會繼續。
您的問題有兩種解決方案:
保持nextInt
int inputexception = 0;
do {
inputexception = 0;
try {
System.out.println("What piece would you like to move?");
pieceselectioninput = scan.nextInt();
} catch ( InputMismatchException e ){
// Get the next line so it won´t repeat forever
scan.nextLine();
inputexception = 1;
}
} while ( inputexception == 1 );
直接使用nextline語句進行解析:
int inputexception = 0;
do {
inputexception = 0;
try {
System.out.println("What piece would you like to move?");
String input = scan.nextLine();
pieceselectioninput = Integer.parseInt(input);
} catch ( NumberFormatException e ){
inputexception = 1;
}
} while ( inputexception == 1 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.