0

Brief description

I am currently writing a massive (For my skill level) java program with my first UI. My goal is to make the program use the UI to save career information to a text file and allow it to read that file into a JTable, these two actions are done through JButtons.

The file uses a # between variables and is in the format:

name#placeOfWork#description#highestSalary#lowestSalary#indexOfDegree#indexOfDegreeLevel and studYears#yearOfMatriculation#

The issue arose when I tried to instantiate a Career constructor (Code below) from the file by splitting the line into the necessary parts, I have no idea how this is giving me an ArrayIndexOutOfBounds exception as it seems to be within the array's boundaries...


The Career's parameterised constructor: (Career)

public final int[] ARR_STUDY_YEARS = { 0, 0, 1, 2, 4, 6, 10 };
public final String ARR_DEGREE[] = { "None", "Commerce", "Science", "Arts", "Computer Sciences", "Education",
        "Medicine", "Engineering" },
        ARR_DEGREE_LEVEL[] = { "None", "Matriculent", "Undergraduate", "Associate", "Bachelor", "Masters",
                "Doctorate" };

// Variables
private String name, setting, description, degree, degreeLevel, qualification;;
private int highestSalary, lowestSalary, avgSalary, sYears, matricYear;

public Career(String name, String setting, String description, int highestSalary, int lowestSalary,
        int degreeNo, int degreeLevelNo, int matricYear){
    this.name = name;
    this.setting = setting;
    this.description = description;
    this.highestSalary = highestSalary;
    this.lowestSalary = lowestSalary;
    sYears = ARR_STUDY_YEARS[degreeLevelNo];
    degreeLevel = ARR_DEGREE_LEVEL[degreeLevelNo];
    degree = ARR_DEGREE[degreeNo];
    this.matricYear = matricYear;
}

The Code giving me an error: (CareerUI)

JButton btnDisplay = new JButton("Display");

    btnDisplay.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            ArrayList<Career> careerList = new ArrayList<Career>();

            File file = new File("Careers.txt");

            try {
                Scanner reader = new Scanner(file);
                while (reader.hasNextLine()) {
                    String[] line = reader.nextLine().split("#");
                    Career career = new Career(line[0], line[1], line[2], Integer.parseInt(line[3]), Integer.parseInt(line[4]),
                            Integer.parseInt(line[5]), Integer.parseInt(line[6]), Integer.parseInt(line[7])); 
                //^ This constructor is on line 200

                    careerList.add(career);
                }
                reader.close();
                String[][] cMatrix = new String[careerList.size()][6];
                String[] header = { "Name", "Setting", "Description", "Average Salary", "Tertiary Qual. Required",
                        "Qualification" };
                for (int i = 0; i < cMatrix.length; i++) {
                    for (int j = 0; j < cMatrix[i].length; j++) {
                        Career c = careerList.get(j);
                        cMatrix[i] = c.toTableSummary();
                    }
                }
                JTable table = new JTable(cMatrix, header);
                // table.set
                table.setBounds(519, 53, 489, 437);
                panel.add(table);
            } catch (FileNotFoundException ex) {
                System.out.println("There was an error while reading your file");
            }

        }
    });

The File: (Careers.txt)

Chartered Accountant#Office#Balances finances#100000#80000#1#4#2017#
Plumber#House Calls#Fixes Plumbing#50000#10000#0#0#2019#
Doctor#Clinic#Treats illness#150000#50000#6#6#2016#
Architect#Construction Firm#Designs Buildings#80000#50000#6#5#2018#

The Error:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
at career.CareerUI$3.actionPerformed(CareerUI.java:200)

Update

Just did a test with converting a text file into a multi dimensional array and it worked, the code is below. I might be close to figuring this out.

public class ScanToArray {
public static void main(String[] args) {
    try {
        Scanner scFile = new Scanner(new File("test.txt"));
        int x = 0;
        String[][] multi = new String[5][5];
        while (scFile.hasNextLine()){
            String[] next = scFile.nextLine().split("#");
            multi[x][0] = next[0];
            multi[x][1] = next[1];
            multi[x][2] = next[2];
            multi[x][3] = next[3];
            multi[x][4] = next[4];
            x++;
        }
        scFile.close();
        int ln = 0;
        for (int i = 0; i < multi.length; i++) {
            for (int j = 0; j < multi[i].length; j++) {
                if(i>ln){
                    System.out.println();
                    ln = i;
                }
                System.out.print("|" +multi[i][j] +"|");
            }
        }
    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, "Error: File not found");
    }
}
}

The File used (test.txt)

0.0#0.1#0.2#0.3#0.4
1.0#1.1#1.2#1.3#1.4
2.0#2.1#2.2#2.3#2.4
3.0#3.1#3.2#3.3#3.4
4.0#4.1#4.2#4.4#4.4

The output:

|0.0||0.1||0.2||0.3||0.4|
|1.0||1.1||1.2||1.3||1.4|
|2.0||2.1||2.2||2.3||2.4|
|3.0||3.1||3.2||3.3||3.4|
|4.0||4.1||4.2||4.4||4.4|

Going to mess around and see if I can convert that to a Jtable and then try to work out where I went wrong initially.

Note: I am not asking what a arrayindexoutofbounds is, I am asking why this particular code is giving me it.

  • So you never ever checked which line of your text file causes this exception? Why? – Tom Nov 21 '16 at 04:24
  • @Tom The first line that my program attempts to convert gives the error – Lord Thanatos Nov 21 '16 at 04:31
  • 1
    Then your issue is not reproducable with the information you've given use. Try to build a [mcve]. And if the first line causes the exception, then print what your code actually reads, since this is not what you've showed us here (your text file example is fine). – Tom Nov 21 '16 at 04:43
  • 1
    @Tom Thanks for that information, I am trying some stuff now, I think I might be on to something... – Lord Thanatos Nov 26 '16 at 09:49

2 Answers2

3

There are few problems with your code:

(1) In the 4th line of your input, there is 7th index (if you split with #), which breaks when you try to get line[7], which will throw ArrayIndexOutOfBoundsException

Buildings#80000#50000#6#5#2017#

(2) You will not be able to parse the 6th element using Integer.parseInt(line[6]) as it throws NumberFormatException

(3) The input data is not right even in the 3rd line, it has more than 7 indexes after split, which does not throw any exceptions (as you are retrieving upto 7 indexes), but ensure that correct data is passed as input.

Vasu
  • 21,832
  • 11
  • 51
  • 67
0
sYears = ARR_STUDY_YEARS[degreeLevelNo];
degreeLevel = ARR_DEGREE_LEVEL[degreeLevelNo];

You most likely don't want to use the same variable as index to different arrays.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • The reason I did that is so that certain levels of study (e.g. Doctorate) use a certain number of study years (e.g 10 years) – Lord Thanatos Nov 06 '16 at 11:21