我正在使用一种扫描器方法供用户输入字符串中的一个单词,但是即使用户输入了字符串之一,其他单词仍在执行。我该如何预防?
public static void main(String[] args) {
while(true) {
StringBuffer StringBuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Hi, what are you trying to find?");
System.out.println("mass");
System.out.println("vol");
System.out.println("temp");
System.out.println("sphere");
System.out.println("density");
String convert = input.nextLine();
if (String.valueOf(convert).contains("mass, volume, sphere, temp, density, pound, ounce, ton, gram,")) {
StringBuffer.append(String.valueOf(convert));
} else {
System.out.println("Wrong input. Try again.");
}
}
}
最佳答案
反之,请在您的变体字符串上调用contains
。正如Clone Talk所述,您不需要String.valueOf
,因为convert
已经是String
(尽管它也可以使用它)。
public static void main(String[] args) {
while (true) {
StringBuffer StringBuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Hi, what are you trying to find?");
System.out.println("mass");
System.out.println("vol");
System.out.println("temp");
System.out.println("sphere");
System.out.println("density");
String convert = input.nextLine();
if ("mass, volume, sphere, temp, density, pound, ounce, ton, gram,".contains(convert)) {
StringBuffer.append(convert);
} else {
System.out.println("Wrong input. Try again.");
}
}
}
解决意见:
为什么
if(convert.contains("...."))
不起作用?最简单的方法是查看the documentation of
String.contains
:当且仅当此字符串包含指定的char值序列时,返回true。问题的原始示例中的这个字符串(不是我的答案)是
convert
,可以是"mass"
或"volume"
等。char值的指定序列是该长字符串
"mass, volume, ..."
。因此,例如
"mass"
可以包含"mass, volume, etc."
吗?确实是另一回事:"mass, volume, etc.".contains("mass") == true
HashSet.contains会更高效
在此示例中,字符串看起来似乎不足以感觉到性能的提高,但是通常来说,这是个好主意,尤其是在可能的输入数量不小的情况下,以及为了提高可读性和可维护性。您可以像这样:
// This part may vary:
private static String [] variants = {"mass", "volume", "sphere", "temp", "density", "pound", "ounce", "ton", "gram"};
private static Set<String> inputs = new HashSet<>(Arrays.asList(variants));
public static void main(String[] args) {
while (true) {
StringBuffer StringBuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Hi, what are you trying to find?");
System.out.println("mass");
System.out.println("vol");
System.out.println("temp");
System.out.println("sphere");
System.out.println("density");
String convert = input.nextLine();
if (inputs.contains(convert)) {
StringBuffer.append(convert);
} else {
System.out.println("Wrong input. Try again.");
}
}
}