问题描述
- Java二维数组存储一位数组的问题
-
从一个txt文件中读出字符串,每一行输出一个record,但我想把所有record中的字符串存放到一个字符数组中,便于我下一步单个字符分析,该怎么改啊import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; class test2 { public static void main(String[] args) { test2 t = new test2(); t.readMyFile(); } void readMyFile() { String record; int recCount = 0; char[] a; char[][] b=new char[10][]; int i=0; int j=0; try { FileReader fr = new FileReader("D:\data.txt"); BufferedReader br = new BufferedReader(fr); while ((record = br.readLine()) != null) { recCount++; a=record.toCharArray(); System.out.println(recCount + ": " + record); System.out.println(a[j]); for(;j<a.length;j++) { b[i][j]=a[j]; } i++; //System.out.println(b[i][j]); } br.close(); fr.close(); } catch (IOException e) { System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } }
解决方案
b的第二维要先初始化,建议使用List<String>
,如果你不能确定长度的话。
解决方案二:
http://blog.sina.com.cn/s/blog_6e10627f0100n0ba.html
解决方案三:
public class test2 {
public static void main(String[] args) {
test2 t = new test2();
t.readMyFile();
}
void readMyFile() {
String record;
ArrayList<char[]> charLists = new ArrayList();//变成这样
char[] a;
try {
FileReader fr = new FileReader("D:\data.txt");
BufferedReader br = new BufferedReader(fr);
while ((record = br.readLine()) != null) {
a=record.toCharArray();
charLists.add(a);
}
br.close();
fr.close();
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
}
}
解决方案四:
用集合吧,把数据放进集合里面再遍历,跟数组差不多
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class test2 {
public static void main(String[] args) {
test2 t = new test2();
t.readMyFile();
}
void readMyFile() {
String record="";
List<String> lists = new ArrayList<String>();
int i=0;
int j=0;
try {
FileReader fr = new FileReader("D:\data.txt");
BufferedReader br = new BufferedReader(fr);
while ((record = br.readLine()) != null) {
lists.add(record);
record="";
}
br.close();
fr.close();
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
}
}
时间: 2024-10-20 08:15:23