我需要进行一些数据验证,以确保用户输入这4个选项(小,中,大,超大)中的4个之一
我从未使用String进行数据验证,
必须有另一种方法来工作吗?
public static String orderSize()
{
System.out.println("What size - small, medium, large, or super size?");
String sizeChoice=input.nextLine();
while (sizeChoice != "small" + "medium" + "large" + "super");
{
System.out.println("Must be one of the sizes listed above here.");
System.out.println("What size - small, medium, large, or super size?");
sizeChoice=input.nextLine();
}
return sizeChoice;
最佳答案
老实说,您还挺有经验的,我建议您首先创建一个包含可能选择的集合。
Set<String> choices = new HashSet<>(Arrays.asList("small","medium","large", "super"));
然后只需将您的while循环条件更改为:
while (!choices.contains(sizeChoice)){...} // while the chosen size is not in the set of choices then keep looping...