我正在創建一個簡單的程序,使用java語言,它使用一堆類似的方法從用戶檢索信息。我用來處理用戶輸入無效數據的方法對我來說似乎非常不正確,因此我正在尋求有關如何更好地處理無效數據的專業指導。Java:更容易的方式來重新提示用戶輸入無效數據時輸入
我試圖搜索類似的問題,但沒有找到。
這是我的方法之一的樣本:
public static int getInput()
{
int temp = 1;
do
{
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
}
}while(temp > 15 || temp < 1);
//This value will never be reached because the do while loop structure will not end until a valid return value is determined
return 1;
}//End of getInput method
有沒有更好的方式來寫這個方法?
這個問題是完全組成的,所以我可以學習一個更好的方法來實現我的未來計劃。
正在使用帶標籤的break語句是否可以接受?如:
public static int getInput()
{
int temp = 1;
start:
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
break start;
}
}
非常感謝您提前。
看起來不錯。順便說一句,爲什麼你不使用GUI? AWT/SWT /擺動....?在那種情況下,你有很多選擇。一個是InputVerifier - http://stackoverflow.com/questions/12997742/java-swing-implementing-a-validy-check-of-input-values – Jayan
@Jayan我只是想學習一個新的概念;不需要GUI來說明問題。必須有更好的方法來做到這一點,最後的返回語句永遠不會到達,並且檢查temp是否在兩次允許的值內。編輯:對不起,我沒有注意到最後一句;我想在沒有GUI的情況下做到這一點。 – Singh