其他的方式,呼籲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("...."))
」 t有效?
最簡單的方法就是看看the documentation of String.contains
:返回true當且僅當此字符串包含焦炭的指定序列值。
此字符串在原始例如,從中心(未在回答)是convert
,其可以是或"mass"
或"volume"
等;
指定的字符值序列是那個長字符串"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.");
}
}
}
你不需要的String.valueOf(轉換),只是做轉換。 – Locke