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.(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)