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

4
  • how do you mean? do you want to merge all? Commented Sep 24, 2020 at 23:52
  • I want to print out all the lines from the list to the screen, that's it. Commented Sep 25, 2020 at 0:09
  • Is there a reason why all your code is in a static initializer block? Commented Sep 25, 2020 at 1:18
  • Actually no, the teacher said to write this in the class on the similar example Commented Sep 25, 2020 at 1:21

3 Answers 3

2

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

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

Sign up to request clarification or add additional context in comments.

5 Comments

Is ChemicalElement your class?
If you change your constructor to the following, (element, int number, String symbol, double[ ]vals) Then the values will be in an array. The array will vary in length depending on the size passed to the constructor. Your example indicated that you were passing in different sized arrays.
public ChemicalElement(String element, int number, String symbol, double[]vals){ this.element = element; this.number = number; this.symbol = 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]; }
I have created this thing, but it's still not working
Previous answer worg´ked, but i had to change constructor to make it work
2

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

1 Comment

your constructor takes primitive double, int I modified the code to accommodate that.
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.

1 Comment

It's just a part of an assignment, I need it as numbers to work with it later. But now I have a trouble with it((

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.