[英]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.