简体   繁体   中英

Array Index Out Of Bounds Exception Issue

I'm currently receiving an out of bounds issue in my array and I'm really unsure where exactly I've went wrong here. I'm really looking for a second pair of eyes over this thing as I'm going to lose my mind.

I honestly appreciate any help given. No really: Thanks.

package com.jpmorgan.spring.csv;

import java.io.BufferedReader;  
import java.io.FileNotFoundException;  
import java.io.FileReader;  
import java.io.IOException;

public class CSVRead {  
    static void read() throws IOException { 
        String csvFileToRead = "profit.csv";  
        BufferedReader br = null;  
        String line = "";  
        String splitBy = ",";  

        try {  
            br = new BufferedReader(new FileReader(csvFileToRead));  

            while ((line = br.readLine()) != null) { 
                String[] array = line.split(splitBy);  
                System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name="  + array[1] + " , Quantity=" + array[2] 
                                + " , Buy=" + array[3] + " , Sell=" + array[4] +  /*" , Coupon=" + array[5] +*/ "]");
            }

        } 
        catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }
        catch (IOException e) {  
            e.printStackTrace();  
        }
        finally {  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }
            } 
        }
        System.out.println("Done reading CSV file");
    }
}

This is the full CSV file. I've tried using debug but it's not been much help.

instrument_type,name,quantity,buy_price,sell_price,coupon
Equity,AAA,123,1.01,1.10
Equity,BBBB,3,1.05,1.01
Bond,CCC,3,,,0.13
Equity,AAA,12,1.11,1.13
Bond,DD,3,,,1.24

Main class for reference.

/**
 * Main class is menu driven, receives CSV input.
 * This program reads, calculates and writes CSV files.
 * @author David McNeill
 * @version 1.0 - 17/03/1015
 */

package com.jpmorgan.spring.csv;
import java.util.Scanner;   
public class CSVMain{

    public static void main(String[] arg) throws Exception {
        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);
        int userChoice;
        boolean quit = false;
        do {
        System.out.println("Please choose an option using 1 - 4");                      //print text to screen
        System.out.println("------------------------------------");                     //print text to screen
        System.out.println("1: Read 'input' CSV file");                                 //print text to screen
        System.out.println("2: Calculate 'input' CSV file");                            //print text to screen
        System.out.println("3: Write calculation result to CSV file");                  //print text to screen
        System.out.println("4: Exit program");                                          //print text to screen
            userChoice = in.nextInt();                                                  //'in' equals integer
            if (userChoice == 4)                                                        //when '3' is input then...
                  quit = true;                                                          //the program will now quit
            else if (userChoice == 1)                                                   //when '1' is input then...
                    CSVRead.read();
            else if (userChoice == 2);
                //####################calculations go here#########################             
                //####################calculations go here#########################
                //####################calculations go here#########################
            else if (userChoice == 3)
                    CSVWrite.write();
        } while (!quit);
    }
}

After splitting the line you should make sure you're getting the right number of columns.

I can't tell you how to fix the potentially bad data but I can help you identify it. Just replace the inner loop with this:

int lineNum = 0;
while ((line = br.readLine()) != null) { 
    String[] array = line.split(splitBy);
    if (array.length < 5)
        throw new Exception("There's a problem with " + csvFileToRead + " on line " + lineNum + ":\n" + line);          
    System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name="  + array[1] + " , Quantity=" + array[2] 
                            + " , Buy=" + array[3] + " , Sell=" + array[4] +  /*" , Coupon=" + array[5] +*/ "]");
    lineNum++;
}

your CSVRead has no main method.. change the call to CSVRead.read();

import java.util.Scanner;   
public class CSVMain{

    public static void main(String[] arg) throws Exception {
        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);
        int userChoice;
        boolean quit = false;
        do {
        System.out.println("Please choose an option using 1 - 4");                      //print text to screen
        System.out.println("------------------------------------");                     //print text to screen
        System.out.println("1: Read 'input' CSV file");                                 //print text to screen
        System.out.println("2: Calculate 'input' CSV file");                            //print text to screen
        System.out.println("3: Write calculation result to CSV file");                  //print text to screen
        System.out.println("4: Exit program");                                          //print text to screen
            userChoice = in.nextInt();                                                  //'in' equals integer
            if (userChoice == 4)                                                        //when '3' is input then...
                  quit = true;                                                          //the program will now quit
            else if (userChoice == 1)                                                   //when '1' is input then...
                    CSVRead.read();
            else if (userChoice == 2);
                //####################calculations go here#########################             
                //####################calculations go here#########################
                //####################calculations go here#########################
        } while (!quit);
    }
}

CSVRead.java

import java.io.BufferedReader;  
import java.io.FileNotFoundException;  
import java.io.FileReader;  
import java.io.IOException;

public class CSVRead {  
    static void read() throws IOException { 
        String csvFileToRead = "profit.csv";  
        BufferedReader br = null;  
        String line = "";  
        String splitBy = ",";  

        try {  
            br = new BufferedReader(new FileReader(csvFileToRead));  

            while ((line = br.readLine()) != null) { 
                String[] array = line.split(splitBy);  
                System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name="  + array[1] + " , Quantity=" + array[2] 
                                + " , Buy=" + array[3] + " , Sell=" + array[4] +  /*" , Coupon=" + array[5] +*/ "]");
            }

        } 
        catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }
        catch (IOException e) {  
            e.printStackTrace();  
        }
        finally {  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }
            } 
        }
        System.out.println("Done reading CSV file");
    }
}

OUTPUT

Please choose an option using 1 - 4
------------------------------------
1: Read 'input' CSV file
2: Calculate 'input' CSV file
3: Write calculation result to CSV file
4: Exit program
1
Equity & Bonds: [Instrument Type= instrument_type , Name=name , Quantity=quantity , Buy=buy_price , Sell=sell_price]
Equity & Bonds: [Instrument Type= Equity , Name=AAA , Quantity=123 , Buy=1.01 , Sell=1.10]
Equity & Bonds: [Instrument Type= Equity , Name=BBBB , Quantity=3 , Buy=1.05 , Sell=1.01]
Equity & Bonds: [Instrument Type= Bond , Name=CCC , Quantity=3 , Buy= , Sell=]
Equity & Bonds: [Instrument Type= Equity , Name=AAA , Quantity=12 , Buy=1.11 , Sell=1.13]
Equity & Bonds: [Instrument Type= Bond , Name=DD , Quantity=3 , Buy= , Sell=]
Done reading CSV file

ALTERNATIVELY, rename read method to main in CSVRead

class public class CSVRead {  
    static void main() throws IOException { 

then call it like you do CSVRead.main(); in CSVMain class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM