如何将值放置到不同的arraylist?

时间:2019-12-20 18:34:16

标签: java arrays arraylist project

我正在做一个餐厅模拟项目。但是,我陷入了代码的反馈部分。我将顾客的食物拿到ArrayList上,关于这个ArrayList,该程序可以针对每种食物一个个地问一个问题,并从顾客那里获得一个价格值。但是我不能将它们放入不同的ArrayLists中。我想这样做是因为关于食物的比率,该程序应显示收视率最高的食物。

简而言之,我想将费率放在不同的数组中。

public static ArrayList FeedBack(ArrayList<String> foods) {
    int foodtype;
    int rate;
    for (int i = 0; i < foods.size(); i++) {
        System.out.printf("%s", foods.get(i));
        System.out.println("");
        System.out.println("please rate that food out of 5");
        Scanner feedbackk = new Scanner(System.in);
        rate = feedbackk.nextInt();
        if ((foods.get(i)).equals("Fried Fries")) {

            RateOfFriedFries.add(rate);
            AllTheFoodRates.add(RateOfFriedFries);
        } else if (foods.get(i).equals("Meat Bal")) {
            RateOfMeatBall.add(rate);
            AllTheFoodRates.add(RateOfMeatBall);
        }
    }
    return AllTheFoodRates;
}

1 个答案:

答案 0 :(得分:0)

执行以下操作:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        //Test
        List<String> foods=Arrays.asList("Fried Fries","Meat Bal");
        System.out.println(feedBack(foods));
    }
    public static List<ArrayList> feedBack(List<String> foods){
        int foodType;
        int rating;
        List<ArrayList> ratingOfAllFoods=new ArrayList<ArrayList>();
        List<Integer> ratingOfFriedFries=new ArrayList<Integer>();
        List<Integer> ratingOfMeatBall=new ArrayList<Integer>();
        for(int i=0;i<foods.size();i++)        {
            System.out.printf("%s%n",foods.get(i));
            System.out.print("Please rate that food out of 5: ");
            Scanner feedback=new Scanner(System.in);
            if(feedback.hasNextInt()) {
                rating=feedback.nextInt();
                if ("Fried Fries".equals(foods.get(i))) {
                    ratingOfFriedFries.add(rating);
                    ratingOfAllFoods.add((ArrayList) ratingOfFriedFries);
                }
                else if("Meat Bal".equals(foods.get(i))){
                    ratingOfMeatBall.add(rating);
                    ratingOfAllFoods.add((ArrayList) ratingOfMeatBall);
                }
              } else {
                  System.out.println("Invalid input");
              }
        }
        return ratingOfAllFoods;
    }
}

示例运行:

Fried Fries
Please rate that food out of 5: 3
Meat Bal
Please rate that food out of 5: 4
[[3], [4]]

我还建议您遵循变量和函数的命名约定。