Как установить требуемую длину целого числа в массиве? - PullRequest
0 голосов
/ 22 января 2012

Как разрешить пользователю повторно вводить номер customerID, если он не соответствует длине 5 цифр?

    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
        }

Ответы [ 4 ]

2 голосов
/ 23 января 2012

Вот один из способов сделать это:

while(true)
{
    customerID[i] = myScanner.nextLine();
    if(customerID[i].length() == 5) break;
    System.out.print("Should be of length 5! Try Again: ");
}
1 голос
/ 23 января 2012

(возможно) самое короткое решение для этого:

do
{
    customerID[i] = myScanner.nextLine();
} while(customerID[i].length() != 5);
0 голосов
/ 23 января 2012

Попробуйте вместо этого.По сути, вам не нужно увеличивать индекс, пока у вас нет правильного ввода.

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++;
 }
}
0 голосов
/ 23 января 2012

Вы можете использовать имеющуюся у вас петлю.

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.
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...