我目前在我的數組中遇到了一個越界問題,而且我真的不確定我到底在哪裏出錯了。我真的很想再看看這件事情,因爲我會失去理智。數組索引超出範圍例外問題
我誠摯地感謝任何幫助。 不是:謝謝。
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");
}
}
這是完整的CSV文件。 我試過使用調試,但它沒有太大的幫助。
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 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);
}
}
u能更新與CSV的前幾排的問題做
CSVRead.main();
? – 2015-03-18 21:15:05你的代碼假設'line.split(splitBy)'將返回一個至少有5個條目的數組(6個帶有註釋掉的位)。顯然它不是。所以你必須看看這條線並找出原因。調試器是最好的方法,單步執行代碼。 – 2015-03-18 21:15:18
是的,從'split'方法調試它。此外,如果文件有一些不同的標題,則會導致問題。這就是爲什麼我問前2-3排。 – 2015-03-18 21:16:46