下面你会找到方法规范和我写的匹配方法:
/**
* This method prompts the user for a number, verifies that it is between min
* and max, inclusive, before returning the number.
*
* If the number entered is not between min and max then the user is shown
* an error message and given another opportunity to enter a number.
* If min is 1 and max is 5 the error message is:
* Expected a number from 1 to 5.
*
* If the user enters characters, words or anything other than a valid int then
* the user is shown the same message. The entering of characters other
* than a valid int is detected using Scanner's methods (hasNextInt) and
* does not use exception handling.
*
* Do not use constants in this method, only use the min and max passed
* in parameters for all comparisons and messages.
* Do not create an instance of Scanner in this method, pass the reference
* to the Scanner in main, to this method.
* The entire prompt should be passed in and printed out.
*
* @param in The reference to the instance of Scanner created in main.
* @param prompt The text prompt that is shown once to the user.
* @param min The minimum value that the user must enter.
* @param max The maximum value that the user must enter.
* @return The integer that the user entered that is between min and max,
* inclusive.
*/
public static int promptUser(Scanner in, String prompt, int min, int max) {
//initialize variables
Integer userInput = 0;
boolean userInteger = false;
System.out.print(prompt);//prompts the user for input
userInteger = in.hasNextInt();
while (userInteger == false) {
System.out.println("Expected a number from " + min + " to " + max +".");
in.nextLine();
userInteger = in.hasNextInt();
}
while (userInteger == true) {
userInput = in.nextInt();
while (userInput > max || userInput < min) {
System.out.println("Expected a number from " + min + " to " + max +".");
in.nextLine();
userInteger = in.hasNextInt();
while (userInteger == false) {
System.out.println("Expected a number from " + min + " to " + max +".");
in.nextLine();
userInteger = in.hasNextInt();
}
userInput = in.nextInt();
}
userInteger = false;
}
//userInteger = false;
return userInput; //FIXME
}
不幸的是,当我尝试使用以下值进行测试时: 4 4 五 4 哟 哟哟
当我输入你的时,我打印出两个错误,而不是1。我知道我打印两次相同的print语句,它是while(userInteger = false)循环下的print语句。关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
当你输入&#34;哟哟&#34;在一个请求中,Java将其解释为单个字符串&#34; yo yo&#34;而不是2个不同的字符串&#34; yo&#34;和&#34;哟&#34;。
如果您想要2个不同的错误消息,则需要输入单个&#34; yo&#34;每一次。
答案 1 :(得分:0)
当你有&#34;哟哟&#34;作为输入。 Scanner.nextInt()接收第一个&#34; yo&#34;作为输入并打印您的错误消息,第二个&#34;哟&#34;留在输入缓冲区。 当它第二次调用.nextInt()时,它会接收第二个&#34; yo&#34;它位于缓冲区中,并打印出另一个错误输出。
您可能会重新考虑使用Scanner.nextLine()然后解析输入而不是简单地使用Scanner.nextInt()。
希望这有帮助。