我在从文本文件中读取数据并将其放入二维数组时遇到问题。数据集的样本是:
1,2,3,4,5,6-
1.2,2.3,4.5,5.67,7.43,8
此代码的问题在于它只读取第一行而不读取下一行。任何建议都表示赞赏。
package test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1{
public static void main(String args[])throws FileNotFoundException, IOException{
try{
double[][] X = new double[2][6];
BufferedReader input = new BufferedReader(new FileReader(file));
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
int rowCounter = 0;
while ((line = input.readLine())!= null) {
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
}
}
}
答案 0 :(得分:2)
您是否尝试过Array实用程序?像这样:
while ((line = input.readLine())!= null) {
List<String> someList = Arrays.asList(line.split(","));
//do your conversion to double here
rowCounter++;
}
我认为空白行可能会抛弃你的循环
答案 1 :(得分:1)
尝试:
int rowCounter = 0;
while ((line = input.readLine())!= null) {
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
...
答案 2 :(得分:1)
您的temp
数组分配的唯一位置是while
循环之前。您需要在循环内分配temp
数组,并且在循环之前不要从BufferedReader
读取。
String[] temp;
String line;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine())!= null) {
temp = line.split(delims); // Moved inside the loop.
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
答案 3 :(得分:0)
readLine期望在行尾添加一个新行。你应该用一个空行来读取最后一行或者改为使用read。
答案 4 :(得分:0)
我无法运行代码,但您的一个问题是您只是拆分了第一个文本行。
package Test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1 {
public static void main(String args[]) {
try {
double[][] X = new double[2][];
BufferedReader input = new BufferedReader(new FileReader(file));
String line = null;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine()) != null) {
String[] temp = line.split(delims);
for (int i = 0; i < temp.length; i++) {
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
}
}
}
我格式化了代码,使其更具可读性。
我推迟设置二维数组的第二个元素的大小,直到我知道一行上有多少个数字。