如果用户ID长度不匹配,如何允许用户重新输入该号码?
for (int i = 0; i < 5; i++) {
System.out.println("Enter the 5-digit ID number of your customer "
+ (i + 1) + "'s below:");
customerID[i] = myScanner.nextLine();
if (customerID[i].length() != 5) {
// What code goes here. I just want to make it so they can
// re-enter the customerID
}
答案 0 :(得分:2)
这是一种方法:
while(true)
{
customerID[i] = myScanner.nextLine();
if(customerID[i].length() == 5) break;
System.out.print("Should be of length 5! Try Again: ");
}
答案 1 :(得分:1)
(也许)最短的解决方案:
do
{
customerID[i] = myScanner.nextLine();
} while(customerID[i].length() != 5);
答案 2 :(得分:0)
你可以使用你拥有的循环。
for (int i = 0; i < 5; i++) {
System.out.println("Enter the 5-digit ID number of your customer "
+ (i + 1) + "'s below:");
customerID[i] = myScanner.nextLine();
if (customerID[i].length() != 5) {
// What code goes here. I just want to make it so they can
// re-enter the customerID
i--; // add this.
}
}
答案 3 :(得分:0)
试试这个。基本上,在有有效输入之前,不必增加索引。
int i = 0;
while( i < 5 ) {
System.out.println("Enter the 5-digit ID number of your customer "
+ (i + 1) + "'s below:");
customerID[i] = myScanner.nextLine();
if (customerID[i].length() != 5) {
/* Print an error and do not increment.
* The next line will overwrite the current one. */
} else {
/* Increment and move on */
i++;
}
}