简体   繁体   中英

Reading txt file and making 2d char array

I have a txt file with the following:

%%%%%%%
%Q%&%%%
%%%&&&%
%&%&%%%
%&%&%%%
%&%&&7%
%&%%%&%
%&&&%&%
%%%&&&%

This is just an example -- the text file could be any 2d array (varying width and height and characters).

I want to read it in and make a 2d char array in java.

I am trying to use a scanner method that reads the lines as a string and then converts to a charArray:

String theString = "";
        File fd = new File("input.txt");
        Scanner sc = new Scanner(fd);;
        theString = sc.nextLine();
        try {
            sc = new Scanner(fd);
        } catch (FileNotFoundException e) {
            System.out.println("File not found! Application terminated\n" + e.toString());
            return;
        }

        while (sc.hasNextLine()) {
               theString = theString + "\n" + sc.nextLine();
        }
        sc.close();
        char[][] charArray= theString.toCharArray();

However, the debugger wants me to change to char[] instead of of char[][]

How can I get the desired results?

The str.toCharArray() method output a char[] of the original string. So the workaround is to add it to the char[][] line-by-line instead.

Since you do not know how many lines exactly are there in the input.txt , you cannot pre-determine the char[][] 's size. One way to do so is to add it to an ArrayList so you know the size of the result array. You can then put it back the char[][] .

String theString = "";
        File fd = new File("input.txt");
        Scanner sc = new Scanner(fd);;
        theString = sc.nextLine();
        try {
            sc = new Scanner(fd);
        } catch (FileNotFoundException e) {
            System.out.println("File not found! Application terminated\n" + e.toString());
            return;
        }

        ArrayList<String> lst = new ArrayList<>();

        while (sc.hasNextLine()) {
               lst.add(sc.nextLine());
        }
        sc.close();

        char[][] result = new char[lst.size()][lst.get(0).length()];
        for(int i = 0; i < lst.size(); i++) {
            char[] charArray= lst.get(i).toCharArray();
            result[i] = charArray;
        }        


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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