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 OverflowYou 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();
}
See Comments
for(int i = 0; i < array1.length; i++) //prints out array
{
// Why did you use number ?
System.out.println("1d " + array1[i]); //prints the line from the file
}
// You don't need these now.
// final int ROWS = 7;
// final int COLS = 5;
// This will initialize 2darray of size as required according to length of array1
char[][] 2darray = new char [array1.length][];
for (int i = 0; i < array1.length; i++) // What is `array`?
{
2darray[i]= array1[i].toCharArray();
}
for (int row = 0; row < 2darray.length; row++) // Use actual size of 2darray row
{
for (int col = 0; col < 2darray[i].length; col++) // use actual size of 2darray column
{
System.out.print(2darray[row][col]);
}
System.out.println();
}
>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(); } }
So I'm trying to read a file like this
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMHMMMHH
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.
Scanner scan=new Scanner(System.in);
char inputArray[][] = new char[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
inputArray[i][j] = scan.next().charAt(0);
}
}
Scanner in = new Scanner(System.in);
int rows = scan.nextInt();
int cols = scan.nextInt();
char arr[][] = new char[rows][cols]; // 2D char array
for (int i = 0; i < rows; i++) {
String data = "";
if (in.hasNext()) { // input from user
data = in.next();
} else {
break;
}
for (int j = 0; j < cols; j++)
arr[i][j] = data.charAt(j);
}
// to get a 2D char array
System.out.println(Arrays.deepToString(arr));
The input will be of the form -
4 // no. of rows
5 // no. of columns
10100
10111
11111
10010
to get a 2D char array as-
[[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]
That seems complicated … but still, this is how:
char[][][][] board = new char[3][3][3][3];
This sounds like a Sudoku board. It'd be much, much easier if you defined a 9x9 2D char array, taking care of iterating over the right zones whenever you have to (simply by controlling the looping variables). Trust me, thinking in terms of a 4D array is gonna be a headache.
Create Array Class:
public class 2DChar {
private char[][] elem = new char[3][3];
//getters, setters...
}
Create Array of Array elements:
2DChar[][] 2dCharArray = new 2DChar[3][3];
Initialise it:
for(int i = 0; i < 2dCharArray.lenght(); i++) {
for(int j = 0; j < 2dCharArray[i].lenght(); j++) {
2dCharArray[i][j] = new 2DChar();
//set value, etc...
}
}
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 == ' ')
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)
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);
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
}
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.
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.
You need an array of String, not of chars:
public static String[] ToStringArray(int[][] array) {
String[] ret = new String[array.length];
for (int i = 0; i < array.length; i++) {
ret[i] = "";
for(int j = 0; j < array[i].length; j++) {
ret[i] += array[i][j];
}
}
return ret;
}
The above answers are right; however you may want to use StringBuilder class to build the string rather than using "+=" to concatenate each char in the char array.
Using "+=" is inefficient because string are immutable type in java, so every time you append a character, it will have to create a new copy of the string with the one character appended to the end. This becomes very inefficient if you are appending a long array of char.