java - 当尝试通过读取文件打印二维数组时,我的输出收到 Null

标签 java arrays file multidimensional-array file-io

我尝试从“联系人”读取文件并将其放入名为 sData 的二维数组中。 我试图在控制台窗口上打印内容,但是我在输出中收到空值。 我是否试图以错误的方式打印内容? 代码已交付给我们,但似乎对我没有任何帮助?

Joe - 1111245678
Tom - 3431234567
Lom - 7771234568
King - 76681234567
Dom - 6842234567
 import java.io.*;
import java.util.Scanner;

public class phonenumbers {


    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        File f= new File ("Contacts.txt");
        ReadData(f);






    }
    public static void printArr (String [][] hex) throws Exception{

        for (int row = 0; row < hex.length; row++) {

              for (int column = 0; column < hex[row].length; column++) {

                System.out.print(hex[row][column] + " ");

              }


              System.out.println();

            }
    }

    public static int CountLines(File f) throws Exception {
        int lines = 0;
        Scanner reader = new Scanner (f);

        while (reader.hasNextLine()) {
            String s = reader.nextLine();
            s = s.trim();
            if (s.length() == 0) {
                break;
            }
            lines++;

        }
        reader.close(); 
        return lines;       
    }


    public static String [][] ReadData(File f) throws Exception {
        Scanner reader = new Scanner (f);
        int numLines = CountLines(f);
        String [][] sData = new String [numLines] [];

        for (int line = 0; line <numLines; line++ ) {
            String l = reader.nextLine(); 
            l = l.trim();
            String [] temp = l.split(" ");
            sData [line] = new String [temp.length];
        }
        printArr(sData);
        reader.close();
        return sData;


    }


}
Output
null null null 
null null null
null null null
null null null
null null null

最佳答案

替换

sData [line] = new String [temp.length];

sData [line] = temp;

您当前只是放置了一个与预期数组大小相同的空数组。

关于java - 当尝试通过读取文件打印二维数组时,我的输出收到 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098057/

相关文章:

ruby - 将索引转换为坐标

c - 搜索文件并将其包含的字符串与输入的变量进行比较

php - 将属性/元数据(评论、标题等)写入视频 (PHP/cURL)

java - 防止在 JTextPane 中输入相同的样式

java - android中的客户端服务器

java - Java 中的领域驱动设计 - 将所有原语转换为值对象?

ios - Xcode : Expected method to write array element not found on object of type 'NSArray *' 错误

arrays - 查找 n * m 数组的所有可能组合,不包括某些值

java - JUnit 设置测试用例

c - C语言写入文件