简体   繁体   English

从字符串文件初始化2D数组

[英]initializing a 2D array from a file of string

This is my first time working with 2D arrays. 这是我第一次使用2D阵列。 I am have read a 4 lines of strings from a text file and extracted them character by character. 我已经从一个文本文件中读取了4行字符串,并逐个字符地提取了它们。 I am having trouble initialing an array with those characters Ive extracted. 我在用Ive提取的那些字符初始化数组时遇到麻烦。 I keep getting memory locations when I try to print my array, so Im assuming the array isn't initialized properly. 尝试打印阵列时,我一直在获取内存位置,因此我假设阵列未正确初始化。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢

public class acsiiArt { 公共类acsiiArt {

public static void main(String[] args) throws IOException
{
File file = new File("test.txt");
Scanner inputFile = new Scanner(file);

while (inputFile.hasNext())
{
    inputFile.nextInt(); 
    while (inputFile.hasNext())
    {
        inputFile.nextInt();
    while (inputFile.hasNext())
    {   
        char array [][]= new char[4][4];
        String letters = inputFile.nextLine(); 
        for(int i =0; i < letters.length(); i++)
        {
        char results = letters.charAt(i);
        for (int row = 0; row < 4;row ++)
        {
            array[row] = new char[row+1];
            for (int col =0; col< row+1; col++)
                array[row][col]= results; 
            System.out.println(array);
        }

        }    
    }   
    }
}
}

} }

You're seeing the Object#toSting representation output of the 2D array . 您正在看到2D arrayObject#toSting表示输出。 In this case it would probably be simpler to iterate through the file using nextLine then using substring and toCharArray to create the array. 在这种情况下,使用nextLine然后使用substringtoCharArray创建数组来遍历文件可能会更简单。

I guess the first two integers at the beginning of the file tell the dimensions, right? 我猜文件开头的前两个整数告诉尺寸,对不对? Wrote this from top of my head so maybe it doesn't compile but should give you an idea: 把这个写在我的头上,所以也许它不会编译,但是应该给你一个主意:

public class ACSIIArt {

public static void main(String[] args) throws IOException {
    File file = new File("test.txt");
    Scanner inputFile = new Scanner(file);
    int x = inputFile.nextInt();
    int y = inputFile.nextInt(); 

    char [][] letters = new char[x][y]; 
    int currentLine = 0;
    String line = null;
    while((line = inputFile.nextLine()) != null) {
        for(int i = 0; i < line.length(); i++) {
             letters[currentLine][i] = line.charAt(i);
        }
    }

    for(int i = 0; i < x; i++) {
        for(int j = 0; j < y; j++) {
             System.out.print(letters[i][j]);
        }
        System.out.print(System.getProperty("line.separator"));
    }
 }

This is the basic way. 这是基本方法。 There are more fancy ways to do this, such as line.toCharArray(); 还有更多更有趣的方法,例如line.toCharArray(); but I think it is important you understand the basics first. 但是我认为重要的是要先了解基础知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM