【发布时间】:2014-05-11 23:09:34
【问题描述】:
我正在尝试创建一种将数据导入二维数组的方法。但是不知何故我的方法不起作用,我发现行后代码出错了:
while (dataScan.hasNext())
用于导入的 .txt 文件示例:
##mm1.0
RowCount=10
--/20140925/Grocery/Supermarket/-5.23/600.00
--/20141013/Car Maintenance/Changing Tires/-200.00/500.00
如果行以“--”开头,我希望将代码读取到数组中
public TablePanel()
{
data = new Object[10][5];
}
public void openData()
{
//Initializing Variables and set up directory
fileChooser = new JFileChooser(userDirectory);
//Set File Filter
fileChooser.setFileFilter(filter);
//It will return positive if user decides to save
//null means that the dialog won't be open according
//to specific Frame
int valReturn = fileChooser.showOpenDialog(null);
try { //Need to catch IO Exception here
if (valReturn == JFileChooser.APPROVE_OPTION) {
//Get the selected file into the File
//and initializing the BufferReader to read the content
File file = fileChooser.getSelectedFile();
BufferedReader bufferR = new BufferedReader(new FileReader(file));
//Inputting it into Scanner class for parsing tokens
Scanner fileScan = new Scanner(bufferR);
//Perform the following as long as Scanner class has next
String currentLine;
String dataLine;
Scanner dataScan;
//rowData is for importing data and counting rows
int rowData = 0;
while (fileScan.hasNext())
{
//Putting it into current line
currentLine = fileScan.nextLine();
//Perform the following if the line starts with "--"
if (currentLine.regionMatches(0, "--", 0, 2))
{
//cutting the "--" from the line
dataLine = currentLine.substring(1);
dataScan = new Scanner(dataLine);
//Separate them by "/"
dataScan.useDelimiter("/");
//putting data into data[][]
//Some problem with the following loops
while (dataScan.hasNext())
{
for (int colData = 0; colData < data[0].length; rowData++)
data[rowData][colData] = dataScan.next();
} //End of importing data per line
//increasing rowData by one
rowData++;
} //End of data[][] import loop
}
【问题讨论】: