【问题标题】:Add different size arrays to ArrayList Java向 ArrayList Java 添加不同大小的数组
【发布时间】:2020-09-24 23:49:20
【问题描述】:

我有这个学校项目。有一个包含化学元素列表的 csv 文件。我必须阅读它,添加到数组列表并打印出来。问题是,从这个文件中读取的这些行的大小不同,例如:

  • 锇,76,Os,190.20,5773.16,3273.16,22600,678.39,26.80,
  • 氡,86,Rn,222.02,

而我的代码,看起来像这样

        static{
        try {   
            Scanner scanner = new Scanner(new FileReader("elements.csv"));
            String title = scanner.nextLine();
            while(scanner.hasNext()){
             
                String[] line = scanner.nextLine().split(",");
                ChemicalElement chemicalElement = new ChemicalElement(line[0],Integer.parseInt(line[1]),line[2],Double.parseDouble(line[3]),Double.parseDouble(line[4]),Double.parseDouble(line[5]),
                        Double.parseDouble(line[6]),Double.parseDouble(line[7]),Double.parseDouble(line[8]));
                chemicalElements.add(chemicalElement);
            }
            
            //(String element, int number, String symbol, double weight, double boil, double melt, double density, double vapour, double fusion)
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        } 
    }

打印出 java.lang.ExceptionInInitializerError

java.lang.ArrayIndexOutOfBoundsException

关于如何处理它的任何想法?请... 是因为线长不同还是这里有其他问题?

构造函数:

    public ChemicalElement(String element, int number, String symbol, double weight, double boil, double melt, double density, double vapour, double fusion){

        this.number = number;
        this.symbol = symbol;
        this.weight = weight;
        this.boil = boil;
        this.melt = melt;
        this.density = density;
        this.vapour = vapour;
        this.fusion = fusion;
        
    }

还有例外:

运行: 线程“主”java.lang.ExceptionInInitializerError 中的异常 在 chemistry.Chemistry.allElements(Chemistry.java:21) 在 chemistry.Chemistry.main(Chemistry.java:30) 原因: java.lang.ArrayIndexOutOfBoundsException:6 在 化学.ChemicalElementDAO.(ChemicalElementDAO.java:51) ... 还有 2 个 C:\Users\tatja\AppData\Local\NetBeans\Cache\11.2\executor-sn-ps\run.xml:111: 执行此行时发生以下错误: C:\Users\tatja\AppData\Local\NetBeans\Cache\11.2\executor-sn-ps\run.xml:94: Java 返回:1 BUILD FAILED(总时间:0 秒)

【问题讨论】:

  • 你是什么意思?是否要全部合并?
  • 我想将列表中的所有行打印到屏幕上,就是这样。
  • 您的所有代码都在静态初始化程序块中是否有原因?
  • 其实没有,老师说要在课堂上写这个类似的例子

标签: java arrays arraylist


【解决方案1】:

试试这个。

  • 避免为此使用静态构造函数。
  • 创建start() 方法以脱离静态上下文
  • 然后创建一个全为零的数组。
  • 读入值并酌情转换。
  • 使用参数调用构造函数。那些没有在生产线上提供的 将为零。
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class YourClass {
    
    List<ChemicalElement> chemicalElements = new ArrayList<>();
    
    public static void main(String[] args) {
        YourClass yc = new YourClass();
        // get out of the static context
        yc.start();
    }
    
    public void start() {
        try {
            Scanner scanner =
                    new Scanner(new FileReader("elements.csv"));
            String title = scanner.nextLine();
            
            while (scanner.hasNext()) {
                String[] line = scanner.nextLine().split(",");
                String element = line[0];
                int atno = Integer.parseInt(line[1]);
                String symbol = line[2];
                // Allocates an array for the remainder of the values.
                // This defaults to all zeros.
                // This presumes there will be no more than 9 values
                // per line.       
                double[] values = new double[6];
                for (int i = 0; i < line.length - 3; i++) {
                    values[i] = Double.parseDouble(line[i + 3]);
                }
                
                ChemicalElement chemicalElement = new ChemicalElement(
                        element, atno, symbol, values[0], values[1],
                        values[2], values[3], values[4], values[5]);
                chemicalElements.add(chemicalElement);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

这是我所能提供的最好的信息。如果它不起作用,您应该与您的导师讨论。

【讨论】:

  • 你的课是 ChemicalElement 吗?
  • 如果您将构造函数更改为以下内容,(element, int number, String symbol, double[ ]vals) 那么这些值将在一个数组中。数组的长度会根据传递给构造函数的大小而有所不同。您的示例表明您正在传递不同大小的数组。
  • public ChemicalElement(String element, int number, String symbol, double[]vals){ this.element = element; this.number = 数字; this.symbol = 符号; this.weight = vals[0]; this.boil = vals[1]; this.melt = vals[2]; this.density = vals[3]; this.vapour = vals[4]; this.fusion = vals[5]; }
  • 我已经创建了这个东西,但它仍然无法正常工作
  • 以前的答案工作了,但我必须更改构造函数才能使其工作
【解决方案2】:

使用当前设置,即Chemical 的构造函数,以防您无法更改构造函数,这是一种方法。

             try {   
                Scanner scanner = new Scanner(new FileReader("elements.csv"));
                String title = scanner.nextLine();
                while(scanner.hasNext()){
                 
                    String[] line = scanner.nextLine().split(",");
                    String e1 = null;
                    int e2 = null;
                    String e3 = null;
                    double[] dbls = new double[6];
                    for ( int i = 0; i < line.length; i++ ) {
                       String key = line[i];
                       switch(i) {
                       case 0:
                          e1 = key;
                          break;
                       case 1:
                          try {
                             e2 = Integer.parseInt(key);
                          } catch(NumberFormatException e) {
                          }
                          break;
                       case 2:
                          e3 = key;
                          break;
                       case 3:
                       case 4:
                       case 5:
                       case 6:
                       case 7:
                       case 8:
                          try {
                            dbl[i-3] = Double.parseDouble(key);
                          } catch(NumberFormatException e) {
                          }
                          break;
                       default:
                          break;
                      }     
                }             
 
                ChemicalElement chemicalElement = new ChemicalElement(e1, e2, e3, dbl[0], dbl[1], dbl[2], dbl[3], dbl[4], dbl[5]);
                       
                //(String element, int number, String symbol, double weight, double boil, double melt, double density, double vapour, double fusion)
            } catch (FileNotFoundException ex) {
                System.out.println(ex.getMessage());
            }

【讨论】:

  • 您的构造函数采用原始双精度,我修改了代码以适应它。
【解决方案3】:

我想知道如果数字已经是字符串,为什么还要使用解析数字。如果您只需要将它们添加到列表并打印出来,您应该能够遍历每一行 .length 次并将每个元素添加为字符串。除非我遗漏了什么,否则将所有内容都保存为字符串应该可以省去很多麻烦。

【讨论】:

  • 这只是作业的一部分,我需要它作为数字来处理它。但是现在我遇到了麻烦((
猜你喜欢
  • 2017-03-23
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 1970-01-01
相关资源
最近更新 更多