2013-03-03 56 views
1

在一個while循環中,我使循環在一個無效輸入後不會返回有效答案,並重復「錯誤!無效的客戶類型,請重試。一遍又一遍,直到我關閉程序。如果我第一次輸入R或C作爲輸入,它可以正常工作。當我輸入其他內容時,我收到錯誤消息「錯誤!無效的客戶類型,請重試。」就像我應該是故意的那樣。然而,在輸入r或c後,錯誤再次給我提供了錯誤,並且我所做的任何輸入都會一遍又一遍地返回錯誤消息,直到關閉程序。有人可以告訴我什麼是錯的,在我的代碼造成這種情況?while循環在第一個錯誤之後反覆返回錯誤

public static String getValidCustomerType(Scanner sc) 
{ 
    String customerType = (""); 
     System.out.println("Enter the Customer Type"); 
     customerType = sc.next() ; 
     boolean isValid = false; 
     while (isValid == false) 
     { 
     if (customerType.equalsIgnoreCase("R")|customerType.equalsIgnoreCase("C")) 
     { 
     isValid = true; 
     } 
     else 
     { 
      System.out.println("Error! Invalid customer type. Try again "); 
     } 
     sc.nextLine() ; 
     } 
    return customerType ; 
} 
+0

您需要在循環中每次分配customerType – Steven 2013-03-03 03:20:18

回答

0

您不會在while循環內分配給customerType。更好地將其推向一開始。

public static String getValidCustomerType(Scanner sc) 
{ 
    String customerType = (""); 

     boolean isValid = false; 
     while (isValid == false) 
     { 
      System.out.println("Enter the Customer Type"); 
      customerType = sc.nextLine() ; 
     if (customerType.equalsIgnoreCase("R")|customerType.equalsIgnoreCase("C")) 
     { 
     isValid = true; 
     } 
     else 
     { 
      System.out.println("Error! Invalid customer type. Try again "); 
     } 
     } 
    return customerType ; 
} 
+0

這很有效,非常感謝:) – 2013-03-03 03:37:02

0

我想你必須在while循環內部移動輸入呼叫。否則,customerType變量總是相同的。

public static String getValidCustomerType(Scanner sc) 
{ 
    String customerType = (""); 
     System.out.println("Enter the Customer Type"); 
     // move this to while loop 
     //customerType = sc.next() ; 
     boolean isValid = false; 
     while (isValid == false) 
     { 
     // get input here 
     customerType = sc.next() ; 
     if (customerType.equalsIgnoreCase("R")|customerType.equalsIgnoreCase("C")) 
     { 
     isValid = true; 
     } 
     else 
     { 
      System.out.println("Error! Invalid customer type. Try again "); 
     } 
     sc.nextLine() ; 
     } 
    return customerType ; 
} 
0

試試這個:|(按位OR)是不一樣的||這是一個OR運算符。其次,你不再分配customerType - 修正如下。

while (isValid == false) 
    { 
    if (customerType.equalsIgnoreCase("R")||customerType.equalsIgnoreCase("C")) 
    { 
    isValid = true; 
    } 
    else 
    { 
     System.out.println("Error! Invalid customer type. Try again "); 
    } 
    customerType = sc.nextLine() ; 
    } 
0

我推薦使用帶有標記的do while循環。這保證代碼至少執行once

public static String getValidCustomerType(Scanner sc) { 
     String customerType; 
     boolean isValid = false; 

     System.out.println("Enter the Customer Type"); 

     do { 
      customerType = sc.next(); 

      if (customerType.equalsIgnoreCase("R")|customerType.equalsIgnoreCase("C")) { 
       isValid = true; 
      } else { 
       System.out.println("Error! Invalid customer type. Try again "); 
      } 
     } while(!isValid); 

     return customerType ; 
    }