[英]Checking to see if a String array contains all of the values of another String array (Java)
我是一個新手編碼人員,試圖教自己如何編碼。 我正在嘗試創建一個程序,該程序存儲配方及其相應成分的列表,然后根據用戶輸入的成分來建議配方。 我正在使用帶有字符串鍵(用於配方名稱)和String []的HashMap來表示相應的成分。
我的問題是,當用戶輸入成分(用逗號分隔)時,我似乎無法使用結果值來檢查這些值是否包含在HashMap的相應值中。
當我嘗試調用我的IngredientSearch()方法時,程序返回異常:“線程“ main”中的異常” java.lang.ClassCastException:[Ljava.lang.String;無法在RecipeBox.ingredientSearch上轉換為java.lang.String。 (RecipeBox.java:55)。”
為什么這行不通,我該如何解決?
import java.util.*;
import java.util.Map.Entry;
public class RecipeBox {
private String recipe;
private String name;
private String userInput;
private String randomRecipe;
Scanner input = new Scanner(System.in);
HashMap<String, String[]> recipes = new HashMap<String, String[]>();
public void addRecipe() {
System.out.println("What is the name of your recipe?");
name = input.nextLine();
System.out.println("Enter the ingredients for " + name + " separated by commas:");
recipe = input.nextLine();
String[] ingredientList = recipe.split(",");
recipes.put(name, ingredientList);
}
public void ingredientSearch() {
System.out.println("What ingredients do you have? Please enter your ingredients, separated by commas.");
userInput = input.nextLine();
String[] ingredientList = userInput.split(",");
String check = ingredientList.toString();
Iterator<Entry<String, String[]>> entries = recipes.entrySet().iterator();
while (entries.hasNext()) {
Entry entry = entries.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (value.contains(check)) {
System.out.println("You could make " + key);
}
}
}
String value = (String) entry.getValue();
應該
String[] value = entry.getValue();
您的值是一個String
數組。
首先,您使用的是原始類型Entry
,而應為Entry<String, String[]>
,這將防止發生任何ClassCastException
。 接下來,您必須驗證check
所有元素都包含在value
。 一種簡單的方法是將value
轉換為Set
以允許高效搜索:
List<String> ingredients = List.of(ingredientList);
while (entries.hasNext()) {
Entry<String, String[]> entry = entries.next();
String key = entry.getKey();
String[] value = entry.getValue();
if (Set.of(value).containsAll(ingredients)) {
System.out.println("You could make " + key);
}
}
注意 :可以使用Java 9進行編譯。如果使用的是Java 8或更低版本,則可以使用Arrays#asList
替換對Set#of
和List#of
Arrays#asList
,但是效率較低。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.