繁体   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