gpt4 book ai didi

java - 运算符 '!='无法应用于Java

转载 作者:行者123 更新时间:2023-12-03 08:24:27 25 4
gpt4 key购买 nike

嗨,我无法让我的if语句生效。
如果(foods.iterator()。next()!=餐。午餐)
在这一行中,我收到一个错误,指出运算符'!='无法应用于'comp1110.exam.Q1MealPlan.Food','comp1110.exam.Q1MealPlan.Meal'

 public static Set<List<Food>> getAllMealPlans(Set<Food> foods, int numMeals) {
Set<List<Food>> set = new HashSet<>();
List<Food> aList = new ArrayList<Food>();
System.out.println(aList);
System.out.println(foods.iterator().next().meal);
if (foods.iterator().next().meal == Meal.BREAKFAST){
aList.add(foods.iterator().next());
set.remove(foods.iterator().next());
if (foods.iterator().next() != Meal.LUNCH){

}
}

最佳答案

我创建了一个Test类,它可以帮助您解决问题,代码中有几个问题。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Test {

public static void main(String[] args) {
new Test().test();
}

void test() {
Set<Food> foods = new HashSet<>();
foods.add(new Food("a", Meal.BREAKFAST));
foods.add(new Food("b", Meal.BREAKFAST));
foods.add(new Food("c", Meal.LUNCH));

Set<List<Food>> mealPlans = getAllMealPlans(foods, 0);
mealPlans.forEach(f -> System.out.println(Arrays.toString(f.toArray())));

System.out.println("--------------------");

//I think what you might want is a Map from Meal to List of Foods
Map<Meal, List<Food>> mealPlans2 = getAllMealPlansMap(foods);
mealPlans2.entrySet().forEach(f ->{
System.out.println("Meal: "+f.getKey());
System.out.println(Arrays.toString(f.getValue().toArray()));
System.out.println("");
});
}

public static Set<List<Food>> getAllMealPlans(Set<Food> foods, int numMeals) { //numMeals unused?
Set<List<Food>> set = new HashSet<>();

Iterator<Food> iterator = foods.iterator(); // only instantiate the iterator once(!)
while (iterator.hasNext()) {
Food food = iterator.next(); //only call .next once(!)
List<Food> aList = new ArrayList<Food>();
if (food.meal == Meal.BREAKFAST) {
//set.remove(foods.iterator().next()); //why remove it from the set?.. and by foods.iterator() you create a NEW Iterator which is starting at index 0 again .. and check that you are calling .remove with the correct type
aList.add(food);
if (food.meal != Meal.LUNCH) {
//
}
}

if(!aList.isEmpty()) {//only add the list if its not empty
set.add(aList);
}
}
return set;
}


public static Map<Meal,List<Food>> getAllMealPlansMap(Set<Food> foods) {
return foods.stream().collect(Collectors.groupingBy(f -> f.meal));
}


enum Meal {
LUNCH, BREAKFAST
}

class Food {
String name;
Meal meal;

public Food(String name, Meal meal) {
super();
this.name = name;
this.meal = meal;
}

@Override
public String toString() {
return name + " " + meal;
}
}
}

关于java - 运算符 '!='无法应用于Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64735614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com