[英]Want to read .txt file and load it into a 2D array, and then print it as is
在作业中,我必须读取.txt文件并将其按原样放置到2D数组中。 注意必须是二维数组。
然后,我必须再次打印它。
.txt输入看起来像这样:
WWWSWWWW\n
WWW_WWWW\n
W___WWWW\n
__WWWWWW\n
W______W\n
WWWWWWEW\n
这是我当前拥有的代码,但出现错误,提示它无法解析方法“ add”。 可能与数组初始化程序有关
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new list[][];
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
然后打印输出必须是
WWWSWWWW
WWW_WWWW
W___WWWW
__WWWWWW
W______W
WWWWWWEW
有什么帮助吗? 谢谢!
假定使用2D数组的原因是每个字符都保存在单独的String对象中。 如果我们对文本文件一无所知,我可以这样实现:
public static void main(String[] args) throws FileNotFoundException {
File textFile = new File("D:/trabalho/maze.txt");
Scanner rowsCounter = new Scanner(textFile));
int rows=0;
while (rowsCounter.hasNextLine()) {
rowsCounter.nextLine();
rows++;
}
String[][] data = new String[rows][];
Scanner reader = new Scanner(textFile);
for (int i = 0; i < rows; i++) {
String line = reader.nextLine();
data[i] = new String[line.length()];
for (int j = 0; j < line.length(); j++) {
data[i][j] = line.substring(j, j+1);
}
}
reader.close();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
该实现可以处理未知数量的行以及每行的未知长度。
干得好!
public static void main(String[] str){
Scanner s = null;
try {
s = new Scanner(new File("path\\text.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> list = new ArrayList<String>();
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
Iterator<String> itr= list.listIterator();
while(itr.hasNext()){
System.out.println(itr.next().toString());
}
}
如果您想坚持使用Array,则可能的解决方案是
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new String[10][5];
for(int x = x; s.hasNextLine();x++ ){
for(int i = 0; i < 5 ; i++){
list[x][i] = s.nextLine();
}
}
s.close();
System.out.println(list);
}
因此,您甚至不需要2D数组,因为String
类的行为就像C ++中的char Array。
另一个解决方案是使用ArrayLists
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
ArrayList<String> list = new ArrayList<String>;
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
因此,现在您有了一个随数据量增长的列表,也可以只使用add方法。 这行ArrayList<String>
表示您的arrayList只能存储String类中的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.