[英]How to repeat something until correct input is given in java?
我正在嘗試制作一個應用程序,對於該應用程序的一部分,我需要從用戶那里獲得輸入,說明在1秒內有多少次單擊鼠標。 我希望輸入的值在1-10和給定的任何其他數字(例如0,-1、11)之間,以向他們提供錯誤信息,並要求他們輸入1-10的有效數字。 同樣,如果用戶鍵入任何字符(例如姓名,A,Jo或hello),也會向他們提供錯誤信息,並要求他們提供正確的輸入。 以下是我所擁有的,但它不起作用。
int OrginalMouseClick;
String Mouseclick = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
int Mouseclick2 = Integer.parseInt(Mouseclick);
while (Mouseclick2 < 1 || Mouseclick2 > 10) {
String Mouseclick = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
if (Mouseclick2 >= 1 || Mouseclick2 <10) {
OrginalMouseClick = Mouseclick2;
}
}
我尚未實現不接受名稱,j,A,你好等任何字符的方法,因為我不確定如何做到這一點,請有人告訴我。
編輯:int mouseClick;
do {
while (!str.hasNextInt()) {
String str = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
str.next(); // this is important!
}
String str = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
mouseclick = Integer.parseInt(str);
}
while (mouseclick < 1 || mouseclick > 10);
使用do while
循環而不是while
循環。 這樣,您就可以在測試條件之前至少運行一次循環,在此條件下可以測試輸入。
String input = null;
do {
//get the input from user
} while (isInputValid); //check input validity here
例:
Scanner input= new Scanner(System.in);
do {
System.out.println("Please enter the advertising cost: ");
advertCost = input.nextDouble();
} while (advertCost >= 100000 || advertCost <= 900000);
我添加了有關如何驗證輸入的鏈接
希望這可以幫助!
要求的示例:
int mouseClick;
do {
String str = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
mouseclick = Integer.parseInt(str);
}
while (mouseclick < 1 || mouseclick > 10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.