Java While循环在第一个错误之后反复返回错误
在一个while循环中,我使循环在一个无效输入后不会返回有效答案,并重复错误!无效的客户类型。再试一次。一遍又一遍直到我关闭程序。如果我第一次输入R或C,它工作正常。当我输入任何其他内容并收到错误消息error!无效的客户类型。再试一次。我应该是故意的。然而,在那个错误之后,输入r或c会再次给我错误,我所做的任何输入都会反复返回错误消息,直到我关闭程序为止。有人能告诉我我的代码中有什么错误导致了这个吗Java While循环在第一个错误之后反复返回错误,java,validation,while-loop,Java,Validation,While Loop,在一个while循环中,我使循环在一个无效输入后不会返回有效答案,并重复错误!无效的客户类型。再试一次。一遍又一遍直到我关闭程序。如果我第一次输入R或C,它工作正常。当我输入任何其他内容并收到错误消息error!无效的客户类型。再试一次。我应该是故意的。然而,在那个错误之后,输入r或c会再次给我错误,我所做的任何输入都会反复返回错误消息,直到我关闭程序为止。有人能告诉我我的代码中有什么错误导致了这个吗 public static String getValidCustomerType(Scann
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 ;
}
我认为您必须将输入调用移动到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 ;
}
尝试以下操作:|按位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() ;
}
您不会在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 ;
}
我建议对sentinel使用do while循环。这保证了代码至少被执行
每次在循环中都需要分配customerType
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 ;
}