有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将所需长度设置为数组中的整数?

如果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) 个答案

  1. # 1 楼答案

    试试这个。基本上,在获得有效输入之前,不必增加索引

    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++;
     }
    }
    
  2. # 2 楼答案

    你可以使用你的循环

    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. # 3 楼答案

    以下是一种方法:

    while(true)
    {
        customerID[i] = myScanner.nextLine();
        if(customerID[i].length() == 5) break;
        System.out.print("Should be of length 5! Try Again: ");
    }
    
  4. # 4 楼答案

    (可能)最短的解决方案:

    do
    {
        customerID[i] = myScanner.nextLine();
    } while(customerID[i].length() != 5);