【问题标题】:how to get particular element from ArrayList如何从 ArrayList 中获取特定元素
【发布时间】:2017-03-02 07:11:42
【问题描述】:

您好,我正在解决给我的这个问题,我必须找到索引 id 最少的人的平均工资

import java.util.*;
import java.io.*;

public class Main {
    public static int processData(ArrayList<String> array) {
      for (String elem :array){
       System.out.println(elem);
      }

        return 0;
    }

    public static void main (String[] args) {
        ArrayList<String> inputData = new ArrayList<String>();
        try {
            Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
            while(in.hasNextLine()) {
                String line = in.nextLine().trim();
                if (!line.isEmpty()) // Ignore blank lines
                    inputData.add(line);
            }
            int retVal = processData(inputData);
            PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
            output.println("" + retVal);
            output.close();
        } catch (IOException e) {
            System.out.println("IO error in input.txt or output.txt");
        }
    }
}

程序正在接受来自文本文件的输入,如下所示

282, ij, 11, 1600000
273, cbg, 12, 800000
567, nj, 11, 800000
539, cb, 11, 600000

所以输出将是

11 520000

我能够打印数组列表中的元素,但无法访问特定元素。谁能帮我访问特定元素,在这种情况下是 11,160000 等等?

提前谢谢你

【问题讨论】:

  • 你看过.split()StringTokenizer吗?
  • 首先,你应该学习如何将你的问题分解成更小的问题。之后分别解决每个问题并将它们组合在一起。如果您对特定的较小问题有任何问题,则更容易解决。这不是关于编码,而是处理问题的方式。

标签: java


【解决方案1】:

提示

您可以像这样计算索引 11 的 AVG:

public static int processData(ArrayList<String> array) {
    String[] spl;
    int avg = 0, nbr = 0;

    for (String elem : array) {
        //split your String with ", " and space
        spl = elem.split(", ");
        //the index exist in the 3ed position, so you have to check your index if 11 then you can get its value
        if(spl[2].equals("11")){
            avg+=Integer.parseInt(spl[3]);
            nbr++;
        }
        System.out.println(elem);
    }
    System.out.println((avg/nbr));
    return avg / nbr;
}

当您在代码中打印时,您必须使用:

output.println("11 " + retVal);

希望这能给你一个想法。

【讨论】:

    【解决方案2】:

    您创建一个字符串列表来存储包含多个字段的员工数据。
    您不应该因为它混合数据员工。

    我建议你的总体思路:

    1) 不要将所有信息存储在字符串列表中,而是使用员工列表。

    替换

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

    List<Employee> employees = new ArrayList<Employee>();
    

    2)使用代表一个人的每个读取行来创建一个自定义对象的实例,例如员工。

    所以替换

     inputData.add(line);
    

    通过类似的方式

    String[] token = line.split(",");
    Employee employee= new Employee(Integer.valueOf(token[0]),token[1],Integer.valueOf(token[2]),Integer.valueOftoken[3]));
    employees.add(employee);
    

    3) 在读取文件的迭代过程中,您可以将 Employee 存储在一个变量中,该变量是 id 最小的。

    4) 读取文件后,您知道具有最小 id 的 Employee。因此,您可以在 Employee 列表上进行迭代,并对具有此 id 的 Employee 的薪水求和,并计算此 Employee 的薪水数量。
    循环完成后计算平均值:float avg = sum / (float)count;

    这不是最优化的方式,但它可以胜任。

    【讨论】:

      【解决方案3】:

      以下代码将满足您的需求。

      public class MyMain {
      
          private static String inputFilePath = "/path/to/input.txt";
          private static String outputFilePath = "/path/to/output.txt";
      
          public static int processData(ArrayList<MyData> array) {
              if (array.size() > 0) {
                  int minId = array.get(0).getData3();
      
                  for (MyData elem : array) {
                      if(elem.getData3() < minId) {
                          minId = elem.getData3();
                      }
                  }
      
                  int count = 0;
                  int total = 0;
                  for (MyData myData : array) {
                      if(myData.getData3() == minId) {
                          count++;
                          total += myData.getData4();
                      }
                  }
      
                  System.out.println("Min ID : " + minId + " -- Avg Sal : " + total/count);
              }
      
              return 0;
          }
      
          public static void main(String[] args) {
              ArrayList<MyData> inputData = new ArrayList<>();
              try {
                  Scanner in = new Scanner(new BufferedReader(new FileReader(inputFilePath)));
                  while (in.hasNextLine()) {
                      String line = in.nextLine().trim();
                      if (!line.isEmpty()) // Ignore blank lines
                          inputData.add(new MyData(line));
                  }
                  int retVal = processData(inputData);
                  PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath)));
                  output.println("" + retVal);
                  output.close();
              } catch (IOException e) {
                  System.out.println("IO error in input.txt or output.txt");
              }
          }
      
      }
      
      class MyData {
          int data1;
          String data2;
          int data3;
          int data4;
      
          public MyData() {
              // TODO Auto-generated constructor stub
          }
      
          public MyData(String data) {
              String dataArr[] = data.split(",");
              this.data1 = Integer.parseInt(dataArr[0].trim());
              this.data2 = dataArr[1].trim();
              this.data3 = Integer.parseInt(dataArr[2].trim());
              this.data4 = Integer.parseInt(dataArr[3].trim());
          }
      
          public int getData1() {
              return data1;
          }
      
          public void setData1(int data1) {
              this.data1 = data1;
          }
      
          public String getData2() {
              return data2;
          }
      
          public void setData2(String data2) {
              this.data2 = data2;
          }
      
          public int getData3() {
              return data3;
          }
      
          public void setData3(int data3) {
              this.data3 = data3;
          }
      
          public int getData4() {
              return data4;
          }
      
          public void setData4(int data4) {
              this.data4 = data4;
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        • 2018-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多