在while循环中,我使循环在一次无效输入后不会返回有效答案,并重复“错误!客户类型无效。再试一次。”一直到我关闭程序。如果我第一次输入R或C作为输入正常工作。当我输入任何其他内容时,我收到错误消息“错误!客户类型无效。请重试。”就像我应该是故意的。但是在输入r或c之后的错误再次给出了错误,并且我做的任何输入一遍又一遍地返回错误消息,直到我关闭程序。有人可以告诉我,我的代码中有什么错误导致这个吗?
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 :(得分: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 ;
}
答案 1 :(得分: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() ;
}
答案 2 :(得分: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 ;
}
答案 3 :(得分: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 ;
}