2017-02-07 45 views
1

我正在使用掃描器方法讓用戶輸入字符串中的一個單詞,但即使用戶輸入其中一個字符串,其他字符仍然正在執行。我如何防止這種情況發生?如何在執行if/else時停止其他操作?

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."); 
     } 
    } 
} 
+1

你不需要的String.valueOf(轉換),只是做轉換。 – Locke

回答

1

其他的方式,呼籲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."); 
     } 
    } 
} 
+0

介意解釋爲什麼'if(convert.contains(「....」))'不起作用? – Yousaf

+0

@Yousaf看到我的更新。 – zhelezoglo

+1

'HashSet.contains'會更高效,不過:) –

相關問題