You cannot have variables start with a number in Java. I suggest changing your variables accordingly and trying it out.

char[][] array2 = new char [ROWS][COLS];

for (int i = 0; i < array.length(); i++)
{
    array2[i]= array1[i].toCharArray();   
}

for (int row = 0; row < ROWS; row++)
{
    for (int col = 0; col < COLS; col++)
    {
         System.out.print(array2[row][col]);
    }
    System.out.println();
}
Answer from Bucket on Stack Overflow
🌐
Coderanch
coderanch.com › t › 702630 › java › Storing-chars-Array-text-file
Storing chars into a 2D Array from text file (Beginning Java forum at Coderanch)
The second number in bold int[][] A = new int[3][2]; specifies how many elements inner arrays may hold. Now, since you read-in the line and have it converted to an array of chars, you just need to assign those arrays of chars (which will represent inner arrays) as an elements of an outer array.
🌐
Reddit
reddit.com › r/javahelp › feeding char array into multidimensional char array
r/javahelp on Reddit: Feeding Char Array into Multidimensional Char Array
June 17, 2019 -

>I am trying to complete the following: " Write a program that reads text from a file. Create a 2-dimensional character array that is 6 * 7. Store the characters read in your array in row major order (fill row 0 first, then row 1, etc.). Fill any unused spaces in the 2-D array with the ‘*’ character. If you have more characters than space, ignore the excess characters. Extract the characters from your array in column-major order (pull from column 0 first, then column 1, etc.). Build a new string as you extract the characters. Display the new string. "

>I believe I have completed: Read file, framework for 1D charArray , framework for 2D charArray

I am running into errors on lines 10, 13, 35, 38, and 39. On lines 10 and 13 is a local variable issue which I might be able to figure out. Lines 35, 38, and 39 started when I switched from a single to a multidimensional array, which I'm unsure if I can use the same code like I did. I am a beginner and do not have a strong grasp of what is going on here and any help is appreciated.

This assignment is due tonight and I will be doing my best to complete it, but for learning purposes I really want to know how I can try to fix this regardless of the due date.

Here is my code:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ReadFile {

//open the file//

public static void main(String\[\] args) {

String fileToReadFrom = "C:/TwoDimArray/charArray.txt"; //identifies file

String lineRead="";

try {

	FileReader fileRead = new FileReader(fileToReadFrom); //opens file 

	BufferedReader readBuffer = new BufferedReader (fileRead); //set buffer

	lineRead=readBuffer.readLine();	

}

catch (IOException e) {

	System.out.println("IO Exception");

}

}

public static char\[\] ReadFileToCharArray (String filePath) throws IOException{

	StringBuilder fileData = new StringBuilder (1000); 

	BufferedReader reader = new BufferedReader(new FileReader("C:/TwoDimArray/charArray.txt"));

	//1D charArray vvv//

char[] buf = new char[42];

int numRead = 0;

while ((numRead = reader.read(buf)) != -1) {

System.out.println(numRead);

String readData = String.valueOf(buf, 0, numRead);

fileData.append(readData);

buf = new char[1024];

}

	//2D charArray vvv//

}

	char\[\]\[\] buf =new char\[6\]\[7\];

	int numRead = 0;

	while ((numRead = reader.readLine(buf)) != -1) {

		System.out.println(numRead);

		String readData = String.valueOf(buf, 0, numRead);

fileData.append(readData);

buf = new char [6][7];

	}

	reader.close();

	return fileData.toString().toCharArray();

	}

}
🌐
Reddit
reddit.com › r/javahelp › reading from a file and turning it into a 2d char array
r/javahelp on Reddit: Reading from a file and turning it into a 2d char array
October 26, 2021 -

So I'm trying to read a file like this

MMMMMMMMMMMMMM
MMMMMMMMMMMMMM
MMMMMMMMHMMMHH

and I'm able to read each line successfully, but I'm having trouble making it into a 2d char array. Like I want each letter in each line to be it's own character in the 2d array, but it's not working as intended.

while ((line = br.readLine()) != null) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
for (int h = 0; h < line.length(); h++) {
char value = line.charAt(j);
System.out.println(value);
playerOneBoardList[i][j] = value;
}
}
}
}

Like when I print this, all it gives me is an array full of M's which is not what I want. I also ran this through the debugger and saw that h isn't going to the next line after it's done with the first line, and it's just staying there, so it's always on the first row of M's not going to the next.

Top answer
1 of 3
2
Your triple loop is unnecessary. In fact, you only ever need a single loop to convert a file into a 2d char array. Take a look at the documentation of the String class. There you will find a very helpful method. When you use that method, you can assign a whole row in a single go meaning that the only loop you need is to read the file line by line.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
IncludeHelp
includehelp.com › java-programs › create-a-two-dimensional-array-fill-it-with-given-few-characters.aspx
Program to create a two dimensional array fill it with given few characters in Java
System.out.print("Enter size of the Array : "); int n = Sc.nextInt(); // enter size in given range. if (n < 2 || n > 10) System.out.print("Size out of Range"); else { // declare array object. char A[][] = new char[n][n]; // enter different characters for filling the array System.out.print("Enter first character : "); char c1 = Sc.next().charAt(0); System.out.print("Enter second character : "); char c2 = Sc.next().charAt(0); System.out.print("Enter third character : "); char c3 = Sc.next().charAt(0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Filling the diagonals with third character if (i == j || (i + j) == (n - 1)) A[i][j] = c3; else // Filling all other positions with second character A[i][j] = c2; } } for (int i = 0; i < n / 2; i++) { for (int j = i + 1; j < n - 1 - i; j++) { // Filling the upper positions.
🌐
Java67
java67.com › 2014 › 10 › how-to-create-and-initialize-two-dimensional-array-java-example.html
How to declare and Initialize two dimensional Array in Java with Example | Java67
Each set is again seperated by another special char. Iterate over the arrays and display the information in the following format. The solution to this problems should be generic. id : 01 name : name1 place : hyd id : 02 name : name2 place : pune Note : Do not use any JAVA API to get the output. Use only loops and conditional statements.ReplyDelete ... how can i use 2d ...
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 40921215 › java-2-dimensional-char-array
Java: 2-dimensional char Array - Stack Overflow
December 2, 2016 - You can initialize 2D arrays so that each row has a different number of columns: char[][] c = new char[7][]; c[0] = new char[5]; c[1] = new char[3]; //etc · Share · Share a link to this answer · Copy linkCC BY-SA 3.0 · Improve this answer ...
🌐
Reddit
reddit.com › r/javahelp › checking if a 2d char array contains a value
r/javahelp on Reddit: Checking if a 2D Char array contains a value
May 14, 2020 -

Originally I made a String[][] arr, and used this line to check if it contains a blank/whitespace entry:

boolean bool = Arrays.stream(cells).flatMap(Stream::of).noneMatch(String::isBlank);

I've since realized my array only needed to hold characters, char[][] arr. I tried editing the code but my IDE is telling me that the last bit is invalid because e is of type char[]. I expected e to just be a char. I'm not sure how to fix it.

boolean bool = Arrays.stream(cells).flatMap(Stream::of).noneMatch(e -> e == ' ')
🌐
Reddit
reddit.com › r/learnprogramming › java 2d array char initialization
r/learnprogramming on Reddit: Java 2D array char initialization
May 25, 2019 -

In a method, I'm trying to fill a 2d array of chars with blank spaces, this is the code I have that's related to the array, I'm getting a null pointer exception when I do this:

private char[][] array;; //wordsearch array (array of letters)
array = new char[20][20]; //this is in constructor
  int countSpaces = 0; //counts characters used 
  //making array blank to start
  for(int r = 0; r < rows; r++)
  {
     for(int c = 0; c < cols; c++)
     {
        System.out.println("[" + r + "][" + c + "]");
        array[r][c] = BLANK; //making everything in array blank so 
its easier to check if array is filled

     }
  }

Are there any nuances in initializing a 2d array of chars that I'm unaware of? (made a pastebin with full class code: https://pastebin.com/FLRXuC3x)

Top answer
1 of 2
2

If I have understood it correctly - file format is something like

4 4
FILE
WITH
SOME
INFO

Modify as below

    Scanner scanner = new Scanner(inFile);     
    String[] size = scanner.nextLine().split("\\s");         

    char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];

    for(int i=0; i < rows; i++) {
        array[i] = scanner.nextLine().toCharArray();
    }

Above code is for initialization of you char array. In order to print the same you can do something like

Arrays.deepToString(array);
2 of 2
0

Copying Tirath´s file format:

4 4 FILE WITH SOME INFO

I would pass it into a 2d array as follows:

public static void main(String[] args){

    char[][] receptor = null;   //receptor 2d array
    char[] lineArray = null;    //receptor array for a line

    FileReader fr = null;
    BufferedReader br = null;
    String line = " ";

    try{
    fr = new FileReader("test.txt");
    br = new BufferedReader(fr);

        line = br.readLine();//initializes line reading the first line with the index
        int i = (int) (line.toCharArray()[0]-48); //we convert line to a char array and get the fist index (i) //48 = '0' at ASCII
        int j = (int)(line.toCharArray()[1]-48); // ... get the second index(j)

        receptor = new char[i][j];  //we can create our 2d receptor array using both index

        for(i=0; i<receptor.length;i++){
                line = br.readLine(); //1 line = 1 row
                lineArray = line.toCharArray(); //pass line (String) to char array
            for(j=0; j<receptor[0].length; j++){ //notice that we loop using the length of i=0
                receptor[i][j]=lineArray[j];    //we initialize our 2d array after reading each line
            }
        }

    }catch(IOException e){
        System.out.println("I/O error");
    }finally{
        try {
            if(fr !=null){
            br.close();
            fr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } //end try-catch-finally
}
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 318819 › how-to-program-2-dimensional-array-to-hold-only-a-single-character-in-each-array-pos
java - How to program 2-dimensional array to hold ... | DaniWeb
October 18, 2010 - The observed "double zero" was an initialization/formatting issue, not a 2-character array element. In Java a new char[][] contains the NUL char ('\u0000') in every slot until explicitly set.
Top answer
1 of 3
1

Consider:

import java.util.Arrays;   

public class Ctest {
    public static void main(String[] args) {
        char[][] word= { {'a', 'b'}, {'c', 'd'}, {'e', 'f'} };

        println(word); // format with brackets e.g., [[a, b], [c, d]]
        System.out.println(Arrays.deepToString(word)); // same format

        for (int i = 0; i < word.length; i++) {
            for (int j = 0; j < word[i].length; j++) {
                if (word[i][j] >= 'a' && word[i][j] <= 'f') {
                    word[i][j] = (char) ((word[i][j] - 'a') + '0');
                }
            }
        }

        println(word); // formatted with brackets
        printPlain(word); // formatted without brackets
    }

    public static void println(char[][] word) {
        System.out.print("[");
        for (int i = 0; i < word.length; i++) {
            if (i > 0) System.out.print(", ");
            System.out.print("[");
            for (int j = 0; j < word[i].length; j++) {
                if (j > 0) System.out.print(", ");
                System.out.print(word[i][j]);
            }
            System.out.print("]");
        }
        System.out.println("]");
    }

    public static void printPlain(char[][] word) {
        for (int i = 0; i < word.length; i++) {
            if (i > 0) System.out.print(", ");
            for (int j = 0; j < word[i].length; j++) {
                if (j > 0) System.out.print(", ");
                System.out.print(word[i][j]);
            }
        }
        System.out.println();
    }
}

The main changes I have made are that the values in the array are actually converted (I'm not sure if you want this; you weren't storing any new values back into the array before), the data is handled as char without being converted to String, the conversion is done with a calculation instead of a special case for each value, and converting the data and printing it have been separated from one another.

There are also a few minor changes. The data is now printed in the format you demonstrated, with brackets, there is no assumption that the inner arrays always have exactly two elements, and the class name has been changed to start with a capital letter.

One other minor note. On the line that converts the values from lower case letters to digits, the expression is in parentheses and is cast back to a char. This is because when you add and subtract chars Java performs a widening conversion to int, so to store the value back into the char[][] it is necessary to cast it to char again.

I had forgotten that there is already a method in Java in the java.util.Arrays class to format a multidimensional array with brackets: Arrays.deepToString(word) will give you the same format as the println method above. I had also shown a printPlain method which is similar, but lacks the brackets, if you prefer a cleaner output format. You could also easily modify this method so that it appends to a StringBuilder and returns a String, instead of printing the array directly.

2 of 3
0

Everything is matching up correctly. This is a 2d array so your arrays are printing one by one.

If you don't want them to go on seperate lines then get rid of the System.out.println(); statement at the end of the for loop.

🌐
Java-forums
java-forums.org › new-java › 42228-multidimensional-char-array.html
Multidimensional char array
April 11, 2011 - Hey u r right that the symbols were the same as u described. I just meant to say that it displays symbol.. the code ca[i][j]=(char)i; I wrote it to typecast the integer to char value but it didn't work. Can u suggest me what exactly I need to write instead. for an array having huge number of elements..
🌐
Stack Overflow
stackoverflow.com › questions › 41526787 › i-want-to-store-a-2d-char-array-into-an-arraylist
java - I want to store a 2d Char array into an ArrayList - Stack Overflow
I didn't think showing code would help, plus i wouldn't know what code to show. I can add the method on setting up my 2d array to look like the starting state of a chessboard but i didn't think that would help in finding an answer. ... The string you have provided, C@22etc, is how Java prints arrays by default.
🌐
Quora
quora.com › How-do-I-declare-a-two-dimensional-array-that-can-be-passed-as-a-char-See-comment-for-explanation
How do I declare a two-dimensional array that can be passed as a char**? See comment for explanation.
Answer (1 of 2): From the details comment: > I have a two dimension array of characters. I also have an array of strings of various lengths. I want to use the same function to process both. I have bad news: In C, you can't. At least, you can’t do so directly. There’s a piece missing. I assume...