簡體   English   中英

如何將.txt文件中字符串的每一行中的單個字符掃描到2D數組中?

[英]How do you scan individual characters from each line of string in a .txt file into a 2D array?

首先,感謝您抽出寶貴時間來解決問題。

我已經花費了無數小時來進行全面搜索,但是仍然沒有找到解決我的問題的有效解決方案:如何使用掃描儀將.txt文件中的每一行字符串中的各個字符掃描到未知尺寸的2D數組中?

問題1:如何確定未知.txt文件的列數? 還是有一種更好的方法來使用.nextInt()方法確定未知2D數組的大小,以及如何?

問題2:如何在控制台上打印出2d數組而沒有奇怪的[@#$ ^ @ ^^錯誤?

問題3:如何使掃描儀將從.txt文件讀取的任何字符打印到控制台上(帶有2d數組(是的,我知道,數組數組))?

這是我不完整的代碼,可讓您對問題有所了解:

import java.util.Scanner;
import java.io.File;

public class LifeGrid {

public static void main(String[] args) throws Exception {

    Scanner scanner = new Scanner(new File("seed.txt"));

    int numberOfRows = 0, columns = 0;


    while (scanner.hasNextLine()) {
        scanner.nextLine();
        numberOfRows++;

    }

    char[][] cells = new char[numberOfRows][columns];

    String line = scanner.nextLine(); // Error here
    for (int i = 0; i < numberOfRows; i++) {
        for(int j = 0; j < columns; j++) {
            if (line.charAt(i) == '*') {
            cells[i][j] = 1;
            System.out.println(cells[i][j]);
            }
        }
    }
    System.out.println(numberOfRows);
    System.out.println(columns);
  }
}

曾經使用過的掃描儀無法重置到起始位置。 您必須再次創建一個新實例。 我已經修改了您的代碼,以實現您要執行的操作-

import java.util.Scanner;
import java.io.File;

public class LifeGrid {

public static void main(String[] args) throws Exception {

    Scanner scanner = new Scanner(new File("seed.txt"));

    int numberOfRows = 0, columns = 0;

    while (scanner.hasNextLine()) {
        String s = scanner.nextLine();
        if( s.length() > columns ) columns = s.length();
        numberOfRows++;

    }

    System.out.println(numberOfRows);
    System.out.println(columns);
    char[][] cells = new char[numberOfRows][columns+1];

    scanner = new Scanner(new File("seed.txt"));
    for (int i = 0; i < numberOfRows; i++) {
        String line = scanner.nextLine();
        System.out.println("Line="+line+", length="+line.length());
        for(int j = 0; j <= line.length(); j++) {
            if( j == line.length() ) {
                cells[i][j] = (char)-1;
                break;
            }
            cells[i][j] = line.charAt(j);
        }
    }
    System.out.println(numberOfRows);
    System.out.println(columns);
    for (int i = 0; i < numberOfRows; i++) {
        for(int j = 0; j <= columns; j++) {
                if( cells[i][j] == (char)-1 ) break;
                System.out.println("cells["+i+"]["+j+"] = "+cells[i][j]);
        }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM