将不同大小的数组添加到ArrayList中,Java。

huangapple go评论78阅读模式
英文:

Add different size arrays to ArrayList Java

问题

以下是您提供的代码的翻译部分:

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);
        }
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
}

构造函数:

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;
}

异常信息:

运行时异常:"main" java.lang.ExceptionInInitializerError
	at chemistry.Chemistry.allElements(Chemistry.java:21) 	at
 chemistry.Chemistry.main(Chemistry.java:30) Caused by:
 java.lang.ArrayIndexOutOfBoundsException: 6 	at
 chemistry.ChemicalElementDAO.<clinit>(ChemicalElementDAO.java:51) 	...
 2 more
 C:\Users\tatja\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:111:
 出现以下错误:
 C:\Users\tatja\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:94:
 Java 返回:1 BUILD FAILED (总时间:0秒)
英文:

I have this project for school. There is a csv file with a list of chemical elements. I have to read it, add to array list and print it out. The problem is, that this lines, that read from this file are not of a same size, for example:

  • Osmium,76,Os,190.20,5773.16,3273.16,22600,678.39,26.80,
  • Radon,86,Rn,222.02,

And my code, that looks like this

        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());
        } 
    }

Prints out java.lang.ExceptionInInitializerError

java.lang.ArrayIndexOutOfBoundsException

Any thoughts on how to handle it? Please...
Is it because of a different line lenght or here is another problem?

Constructor:

    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;
        
    }

And exceptions:

> run:
Exception in thread "main" java.lang.ExceptionInInitializerError
> at chemistry.Chemistry.allElements(Chemistry.java:21) at
> chemistry.Chemistry.main(Chemistry.java:30) Caused by:
> java.lang.ArrayIndexOutOfBoundsException: 6 at
> chemistry.ChemicalElementDAO.<clinit>(ChemicalElementDAO.java:51) ...
> 2 more
> C:\Users\tatja\AppData\Local\NetBeans\Cache\11.2\executor-snippets\run.xml:111:
> The following error occurred while executing this line:
> C:\Users\tatja\AppData\Local\NetBeans\Cache\11.2\executor-snippets\run.xml:94:
> Java returned: 1 BUILD FAILED (total time: 0 seconds)

答案1

得分: 2

尝试这个。

  • 避免使用静态构造函数。
  • 创建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();
		// 脱离静态上下文
		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];
				// 为剩余的值分配一个数组。
                // 默认为全零。
                // 这假设每行不会超过9个值。
				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();
		}
	}
}

根据提供的信息,这是我能提供的最佳翻译。如果它不起作用,您应该与您的指导老师讨论。

英文:

Try this.

  • avoid using the static constructor for this.
  • create the start() method to get out of static context
  • then create an array of all zeros.
  • read in the values and convert as appropriate.
  • invoke the constructor with the arguments. Those not supplied in the line
    will be zero.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class YourClass {
List&lt;ChemicalElement&gt; chemicalElements = new ArrayList&lt;&gt;();
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(&quot;elements.csv&quot;));
String title = scanner.nextLine();
while (scanner.hasNext()) {
String[] line = scanner.nextLine().split(&quot;,&quot;);
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 &lt; 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();
}
}
}

This is the best I can offer with the information provided. If it doesn't work you should discuss with your instructor.

答案2

得分: 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 = 0;
        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 {
                        dbls[i-3] = Double.parseDouble(key);
                    } catch(NumberFormatException e) {
                    }
                    break;
                default:
                    break;
            }     
        }             

        ChemicalElement chemicalElement = new ChemicalElement(e1, e2, e3, dbls[0], dbls[1], dbls[2], dbls[3], dbls[4], dbls[5]);
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
英文:

With the current set up i.e. the constructor of Chemical in case you cannot change the constructor, here is one way to do.

             try {   
Scanner scanner = new Scanner(new FileReader(&quot;elements.csv&quot;));
String title = scanner.nextLine();
while(scanner.hasNext()){
String[] line = scanner.nextLine().split(&quot;,&quot;);
String e1 = null;
int e2 = null;
String e3 = null;
double[] dbls = new double[6];
for ( int i = 0; i &lt; 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

得分: 0

我在想,如果这些数字已经是字符串,为什么你需要解析它们呢?如果你只需要将它们添加到一个列表并打印出来,你应该可以通过循环遍历每一行的长度次数,并将每个元素添加为一个字符串。除非我漏掉了什么,保持所有内容都作为字符串,应该能够为你节省很多麻烦。

英文:

I'm wondering why you need to use parse the numbers if they are already strings. If you only need to add them to a list and print them out, you should be able to loop through each line .length times and add each element as a string. Unless I'm missing something, it should save you a lot of trouble to keep everything as a string.

huangapple
  • 本文由 发表于 2020年9月25日 07:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64055886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定