2013-03-03 58 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 ; 
    }