当前位置: 首页 > 知识库问答 >
问题:

如何将双arraylist与字符串arraylist合并

王昆
2023-03-14

我有一项任务,要求我从文本文件中读取配方,并处理计量单位和配料数量等内容。我将配方的各个部分分离到一个数组列表中,以处理配料,因为用户将输入他们是要使用英制单位还是公制单位。从这里,我创建了一个双数组列表,用于从原始列表中分离数量,因此4汤匙盐就变成了4.0。在此之后,用户可以输入是否要更改食谱的份量,因此4.0可以变成任何正数,如8.0。我已经对所有这些进行了编码,直到需要将被操纵的数组列表重新合并在一起以输出给用户为止。因此,原来的字符串数组列表有4种大小:

[2 tbsp olive oil, 3 tbsp garlic, minced, 2 tsp dried parsley, 1 cup eggplant, cut into half inch cubes, 0.5 tbsp salt, 1 cup Parmesan cheese]

必须与新的8种服务尺寸的相应双阵列列表相结合:

[4.0, 6.0, 4.0, 2.0, 1.0, 2.0]

要获取:

[4 tbsp olive oil, 6 tbsp garlic, minced, 4 tsp dried parsley, 2 cup eggplant, cut into half inch cubes, 1 tbsp salt, 2 cup Parmesan cheese]

任何帮助都将不胜感激。

import java.util.*;
import java.io.*;
class Main {

    /**
     * Prints methods to user
     */
    public static void main(String[] args) throws Exception{
        printer1();
        servingReader();
        System.out.println(sSize);
        ingrReader();
        System.out.println(ingrList);
        ingrSeperator();
        System.out.println(SeperatorImperialList);
        choice();
    }//end main

    /**
     * Prints origanal recipe to user
     */
    public static void printer1() throws Exception{
        Scanner sc = new Scanner(new File("/home/runner/recipe.txt"));
        //original text file printed to the user before manipulation
        while (sc.hasNextLine()){
            System.out.println(sc.nextLine());
        }
        sc.close();//scanner closed
    }

    static int sSize;//int for serving size

    /**
     * Reads text file
     */
    public static void servingReader() throws Exception{

        //recipe read
        File recipe = new File("/home/runner/recipe.txt");
        Scanner sc = new Scanner(recipe);

        //loop to find serving size
        while(sc.hasNextLine()){
            String s = sc.nextLine().toUpperCase();
            if(s.equals("SERVING SIZE")){
                sSize = sc.nextInt();
            }
        }

        sc.close();//scanner closed
    }//servingReader

    static ArrayList<String> ingrList = new ArrayList<>();//ArrayList for ingredients created

    static String scan;

    /**
     * Reads recipe and adds ingredients section to list
     */
    public static void ingrReader() throws Exception{

        //recipe read
        File recipe = new File("/home/runner/recipe.txt");
        Scanner sc = new Scanner(recipe);

        //loop to find ingredients section or recipe
        while(sc.hasNextLine()){
            String s = sc.nextLine().toUpperCase();
            //if scanner finds header INGREDIENTS, section added to ingrList
            if(s.equals("INGREDIENTS")){
                while(sc.hasNextLine()){
                    int i = 0;
                    scan = sc.nextLine();
                    ingrList.add(i, scan);
                    i+= 1;
                    //if nothing is found, breaks
                    if(scan.equals("")){
                        break;
                    }
                }
            }
        }
        sc.close();//scanner closed

        Collections.reverse(ingrList);//reverse method reverses order of elements in ingrList

        int ingr1 = ingrList.size() - 1;
        ingrList.remove(ingr1);


    }//ingrReader

    static ArrayList<Double> SeperatorImperialList = new ArrayList<Double>();//ArrayList for seperated ingredients created

    /**
     * Seperates ingredient quantitys from ingredints list and adds to seperated list
     */
    public static void ingrSeperator(){

        double ingr2 = 0;

        for(int i = 0; i <ingrList.size(); i++){
            String split [] = ingrList.get(i).split(" ");
            ingr2 =  Double.parseDouble(split[0]);
            String str = String.format("%1.2f", ingr2);
            ingr2 = Double.valueOf(str);
            SeperatorImperialList.add(ingr2);

        }

    }//end ingrSeperator

    static int unit;
    /**
     * Gets choice of imperial or metric
     */
    public static void choice() throws Exception{
        Scanner sc = new Scanner(System.in);
        System.out.println("Use imperial(1) or metric(2) units");
        System.out.print("Enter 1 or 2: ");//serving size enetered
        unit = sc.nextInt();

        if (unit == 1){
            divideImperial();
        }
        else{
            converter();
        }

        sc.close();//scanner closed

    }//end choice

    //for imperial
    /**
     * Gets serving size input from user and then adjusts seperated ingredinets accordingly for imperial
     */
    public static void divideImperial() throws Exception{
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your Imperial serving size: ");//serving size enetered
        int servingSize = sc.nextInt();

        for(int i=0;i<SeperatorImperialList.size();i++){
            SeperatorImperialList.set(i,SeperatorImperialList.get(i)*servingSize);//origanal quantiys multiplyed by new serving size
        }

        for(int i=0;i<SeperatorImperialList.size();i++){
            SeperatorImperialList.set(i,SeperatorImperialList.get(i)/4);//multiplyed quantitys now divided by origanal serving size 4
        }
        mergImperial();

        sc.close();//scanner closed

    }//end divideImperial

    static ArrayList<String> convertedList = new ArrayList<>();//ArrayList for metric ingredients created

    static ArrayList<Double> SeperatedMetricList = new ArrayList<Double>();//ArrayList for seperated metric ingredients created



    /**
     * Converts imperial to metric
     */
    public static void converter() throws Exception{
        Scanner sc = new Scanner(System.in);

        //convert tbsp to ml
        for(int i = 0; i < ingrList .size(); i++){
            //if ingrList contains tbsp replaced with ml
            if(ingrList.get(i).contains("tbsp")){
                convertedList.add(ingrList.get(i).replace("tbsp", "ml"));
                //for(int j=0;j<ingrSeperatorList.size();j++){
                //ingrSeperatorList.set(j,ingrSeperatorList.get(j)*15);
                //}
            }
        }

        //convert cup to ml
        for(int i = 0; i < ingrList .size(); i++){
            //if ingrList contains cup replaced with ml
            if(ingrList.get(i).contains("cup")){
                convertedList.add(ingrList.get(i).replace("cup", "ml"));

                // for(int j=0;j<ingrSeperatorList.size();j++){
                //   ingrSeperatorList.set(j,ingrSeperatorList.get(j)*250);

                // }
            }
        }

        //convert tsp to ml
        for(int i = 0; i < ingrList .size(); i++){
            //if ingrList contains tsp replaced with ml
            if(ingrList.get(i).contains("tsp")){
                convertedList.add(ingrList.get(i).replace("tsp", "ml"));
                //   for(int j=0;j<ingrSeperatorList.size();j++){
                //       ingrSeperatorList.set(j,ingrSeperatorList.get(j)*5);
                //   }
            }
        }
        SeperatorMetric();

        sc.close();//scanner closed
    }//end converter

     /**
     * Seperates metric list
     */
    public static void SeperatorMetric() throws Exception{

        double ingr2 = 0;

        for(int i = 0; i <convertedList.size(); i++){
            String split [] = convertedList.get(i).split(" ");
            ingr2 =  Double.parseDouble(split[0]);
            String str = String.format("%1.2f", ingr2);
            ingr2 = Double.valueOf(str);
            SeperatedMetricList.add(ingr2);
            divideMetric();
        }

    }//end SeperatorMetric

    /**
     * Gets serving size input from user and then adjusts seperated ingredinets accordingly for metric
     */
    public static void divideMetric() throws Exception{
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your Metric serving size: ");//serving size enetered
        int servingSize = sc.nextInt();

        for(int i=0;i<SeperatedMetricList.size();i++){
            SeperatedMetricList.set(i,SeperatedMetricList.get(i)*servingSize);//origanal quantiys multiplyed by new serving size
        }

        for(int i=0;i<SeperatedMetricList.size();i++){
            SeperatedMetricList.set(i,SeperatedMetricList.get(i)/4);//multiplyed quantitys now divided by origanal serving size 4
        }
        mergMetric();
        sc.close();//scanner closed

    }//end divideImperial

    

    /**
     * Merges imperial lists together
     */
    public static void mergImperial(){
      System.out.print(SeperatorImperialList);
      System.out.println("Imperial");
            //here I would merge the ingredients list with the new serving size list
    }//end mergImperial

    /**
     * Merges metric lists together
     */
    public static void mergMetric(){
      System.out.print(SeperatedMetricList);
      System.out.println("Metric");
            //here I would merge the metric converted ingredients list with the new serving size list
    }//end mergMetric

}//end main

共有3个答案

祝俊
2023-03-14

首先,创建一个内部成分类来保存需要合并的信息。

private static class Ingredient {
    final String name;
    final double quantity
    Ingredient(String name, double quantity) {
        this.name = name;
        this.quantity = quantity;
    }
}

然后更改合并方法(我使用了度量方法)。[我假设转换列表是这里包含成分的列表,如果错误则正确。]

public static void mergMetric() {
  System.out.print(SeperatedMetricList);
  System.out.println("Metric");
        //here I would merge the metric converted ingredients list with the new serving size list
    ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
    int length = Math.Min(SeperatedMetricList.size(), convertedList.size());
    for (int i = 0; i < length; i++) {
        ingredients.add(new Ingredient(convertedList.get(i), SeperatedMetricList.get(i)));
    }
    // The list 'ingredients' should be done now, do whatever you want with it.
}//end mergMetric
佘修为
2023-03-14

您可以创建一个单独的arraylist,并使用for循环将两个值转储在一起,前提是对它们进行适当的索引。

public static void main(String[] args) 
{
    String unit = "Units";

    int indexVariable = 0;

    ArrayList<Double> doubleArrayList = new ArrayList<Double>();
    doubleArrayList.add(0, 0.0);
    doubleArrayList.add(1, 1.0);
    doubleArrayList.add(2, 2.0);
    doubleArrayList.add(3, 3.0);
    doubleArrayList.add(4, 4.0);

    ArrayList<String> stringArrayList = new ArrayList<String>();
    stringArrayList.add(0, "Flour");
    stringArrayList.add(1, "Egg");
    stringArrayList.add(2, "butter");
    stringArrayList.add(3, "water");
    stringArrayList.add(4, "Pot");

    ArrayList<String> combinedArrayList = new ArrayList<String>();

    for(Double d : doubleArrayList) 
    {           
        combinedArrayList.add(indexVariable, "[" + indexVariable + "]: " + d + " " + unit + " of " + stringArrayList.get(indexVariable));

        System.out.println(combinedArrayList.get(indexVariable));
        indexVariable++;
    }
}

您还可以使用douleArrayList.indexOf(d)来替换indexVariable。

龙毅
2023-03-14

您可以使用下面的代码来合并列表

public static List<String> merge() throws Exception{

List<String> newStringList = new ArrayList<>();

        for(int i = 0; i <convertedList.size(); i++){
            String split [] = convertedList.get(i).split(" ");
            split[0] = SeperatedMetricList.get(i).toString();
            String joinedString = String.join(" ", split);
            newStringList.add(joinedString);
        }
       return newStringList;
    }

另请注意:在声明方法和变量时,请遵循命名约定。Java命名转换

 类似资料:
  • 问题内容: 我想遍历每个单独的ArrayList。我不知道如何将字符串转换为适当的ArrayList对象。 问题答案: 这种语法看起来像是JSON的子集,我猜想客户端实际上是将其编码为JSON。假设这是真的,最简单的方法将是使用现成的JSON解析器和一些简单的Java代码将结果对象转换为代码所需的形式。 当然,您可以手动实现自己的解析器,但是这样做可能不值得,尤其是如果您必须处理字符串转义,空格中

  • 问题内容: 我想将ArrayList保存到SharedPreferences,因此需要将其转换为字符串然后返回,这就是我正在做的事情: 我可以用它来检索它,但我不知道如何将arrayString转换回ArrayList。如何做呢? 我的数组看起来像: 问题答案: 您有2个选择: 手动解析字符串并重新创建arraylist。这将是非常乏味的。 使用Google的Gson库之类的JSON库,以JSON

  • 我正在从treemap中获取值: --> 无法按升序对列表进行排序 我从idlatlng获得的值是:[<代码>LAT/LNG:(70.0187,-141.0205),LAT/LNG:(70.4515,-144.8163),LAT/LNG:(70.4515,-144.8163),LAT/LNG:(70.4515,-144.8163),LAT/LNG:(70.4515,-144.8163),LAT/L

  • 本文向大家介绍如何从Java ArrayList创建字符串?,包括了如何从Java ArrayList创建字符串?的使用技巧和注意事项,需要的朋友参考一下 要将ArrayList的内容转换为String,创建一个StringBuffer对象,将ArrayList的内容附加到该对象,最后使用toString()方法将StringBuffer对象转换为String 。 示例 输出结果

  • 问题内容: 我想将数组转换为。例如字符串数组是这样的: 如何将此String数组转换为ArrayList? 问题答案: 为此使用此代码,

  • 问题内容: 我想做这样的事情: 这似乎不起作用。最简单的方法是将多个地址(每个地址3个字段)存储在数组中而不为其创建单独的类,这是最简单的方法吗? 问题答案: 对3个字符串使用第二个ArrayList,而不是原始数组。就是 然后您可以拥有: (我认为这里的类型擦除可能会发生一些奇怪的事情,但我认为这并不重要) 如果您对使用原始数组一无所知,则只需进行较小的更改即可使示例工作。如其他答案所述,数组的