例如:
-8-88-8-8-8--8
-8-8-8-8-8-8-8
*-8-8-8-8--8-8
8--8-8-8-8--8-
答案 0 :(得分:2)
-
拆分字符串,这样你就可以将char数组添加到你的2d char数组中。答案 1 :(得分:2)
最简单的方法是使用String的toCharArray()方法。
因此,如果您使用的是BufferedReader
ArrayList<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("file"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
// finally convert the arraylist to a char[]
char[] firstDimension = new char[list.size()];
for (int i = 0; i < list.length; i++) {
firstDimension[i] = list.get(i).toCharArray();
}
答案 2 :(得分:0)
char [] firsDimension不是2d。尝试类似的事情,
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("/path/to/file/yourfile.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
//print values
for (int i=0;i<firstDimension.length;i++) {
for (int j=0;j<firstDimension[i].length;j++) {
System.out.println(firstDimension[i][j]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
使用扫描仪类
try {
Scanner scanner = new Scanner(new File(
"/home/sinan/Desktop/yourfile.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
list.add(scanner.next());
}
scanner.close();
// finally convert the arraylist to a char[][]
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i = 0; i < firstDimension.length; i++) {
for (int j = 0; j < firstDimension[i].length; j++) {
System.out.println(firstDimension[i][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}