I'm trying to display a multi dimensional char array, but I'm getting an error when trying to display it. Is there a better way to display this? Did I do something wrong somewhere else? I can't figure out what is wrong with my code.
public class recBinTree {
private int left, right, columns, rows;
private char [][]binTree;
public recBinTree(int size){
left = 0;
right = size-1;
columns = size;
double n = Math.log(size)/Math.log(2); //convert to base 2
rows = (int)n + 1; // # of rows = n
char[][] binTree = new char[rows][columns];
//populate entire array with hyphens
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++)
binTree[i][j] = '-';
}//end outer for
}//end constructor
public void display(){
System.out.print("Columns: " + columns + " ");
System.out.print("Rows: " + rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++)
System.out.print(binTree[i][j] + " "); //error on this line
System.out.print("\n");
}//end outer for
}//end display()
public class Driver {
public static void main(String[] args) {
int size = 16;
recBinTree tree = new recBinTree(size);
tree.display(); //error on this call
}
}
Edit:
Sorry here's the error!
Exception in thread "main" java.lang.NullPointerException
at ProjectThreeC.recBinTree.display(recBinTree.java:38)
at ProjectThreeC.Driver.main(Driver.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
try initializing this private char [][]binTree; rather than creating a new array inside the con structure ( char[][] binTree = new char[rows][columns]; ). So the private char [][]binTree; is null every time you try printing. And for printing you can use below:
char[][] c = new char[2][10];
// read the values
//now display
for(int i=0;i<c.length;i++){
System.out.println(String.valueOf(c[i]));
}
public class recBinTree {
private int left, right, columns, rows;
private char [][]binTree;
public recBinTree(int size){
left = 0;
right = size-1;
columns = size;
double n = Math.log(size)/Math.log(2); //convert to base 2
rows = (int)n + 1; // # of rows = n
binTree = new char[rows][columns];
//populate entire array with hyphens
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++)
binTree[i][j] = '-';
}//end outer for
}//end constructor
public void display(){
System.out.print("Columns: " + columns + " ");
System.out.print("Rows: " + rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++)
System.out.print(binTree[i][j] + " "); //error on this line
System.out.print("\n");
}//end outer for
}//end display()
public static void main(String[] args) {
int size = 16;
recBinTree tree = new recBinTree(size);
tree.display(); //error on this call
}
}
You declare char [][]binTree; as instaces and also again declare at contructor. Remove declaration from constructor.
private char [][]binTree;
public recBinTree(int size){
......
binTree = new char[rows][columns]; //Remove char[][] from here
//populate entire array with hyphens
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++)
binTree[i][j] = '-';
}
}
Also you don't need two for loops to fill binTree array with -. Just simply use Arrays.fill operation.
public recBinTree(int size){
......
binTree = new char[rows][columns];
Arrays.fill('-');
}
Do like this
char [][]binTree={{'A','B','C'},{'D','E','F'},{'G','H','I'}};
System.out.println(Arrays.deepToString(binTree));
By doing char[][] binTree = new char[rows][columns]; you are creating a new variable within the scope of the function. You are getting a null pointer exception, because when the application later looks in the binTree-variable for the scope of the entire class, it will find out is empty.
Change it to:
binTree = new char[rows][columns];
This will initialise the binTree-variable for the scope of the entire class.
Related
I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;
I want to swap Columns and Rows in a 2D array.
My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.
Id like to know how I can save the Variable oldField independent
public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
// a Field
int[][] oldField = pField.clone();
int[][] newField = pField.clone();
for (int i = 0; i < newField.length; i++) {
for (int j = (newField.length - 1); j >= 0; j--) {
newField[i][(newField.length - 1) - j] = oldField[j][i];
}
}
return newField;
}
When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
this code solves your problem:
public class SwapRowsAndColumns {
public static void main(String[] args) {
int[][] someMatrix = new int[2][3];
someMatrix[0][0] = 1;
someMatrix[0][1] = 2;
someMatrix[0][2] = 3;
someMatrix[1][0] = 4;
someMatrix[1][1] = 5;
someMatrix[1][2] = 6;
printMatrix(someMatrix);
int[][] invertedMatrix = swapMatrix(someMatrix);
printMatrix(invertedMatrix);
}
private static int[][] swapMatrix(int[][] pField) {
int originalTotalRows = pField.length;
int originalTotalColumns = pField[0].length;
int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];
for(int i=0; i< originalTotalRows; i++){
for(int j=0; j < originalTotalColumns; j++){
newMatrix[j][i] = pField[i][j];
}
}
return newMatrix;
}
private static void printMatrix(int[][] matrix){
int totalRows = matrix.length;
int totalColumns = matrix[0].length;
for(int i=0; i< totalRows; i++){
for(int j=0; j< totalColumns; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
}
}
i need help in getting the array length from another class. i.e., passing the length of array from one class to another. Here is the problem.
Testmatrix.java
public class TestMatrix{
int rows;
int cols;
double data[][] = new double[4][4];
public TestMatrix() {
super();
rows=1; cols=1;
for(int i=0; i<=rows;i++)
{
for(int j=0; j<=cols;j++)
{
data[i][j] = 0.0;
}
}
}
public void print(){
for (int i = 0; i <data.length ; i++) {
for (int j = 0; j <data[0].length ; j++) {
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
Here is the main class
Main.java
public class Main {
public static void main(String[] args){
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
Everything seems right in the constructor. But the problem is the print function. The size of the data should be 2. But its is taking the value of 4 declared that is initialised. Someone solve this for me. I need to get to print 2x2 matrix( with all 0's) but i'm getting 4x4 matrix( with all 0's)
Thanks in advance **
When you create an array, you set the size, for example new double[4][4] then that's already the size of this array, even tho you didn't insert anything in there. My point is that no matter if you insert 1 element, 2 elements, or 8 elements, that doesn't matter, inserting to array doesn't change it's size (property returned by length). Imagine a bag, you have a bag with a certain size, doesn't matter if you put items in there, size of a bag is gonna stay the same.
You declared your array as a 4x4 matrix. Line 4 should be double data[][] = new double[2][2]; in order to achieve what you seem to want.
Initializing array doesn't change the size of an array. If you want to print acording to new row and column size, change your print() method to:
public void print() {
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
Again, constructor name should be same as class name. But the constructor of TestMatrix is Matrix.
Note: Another important thing, you don't need to initialize the double array to 0.0. This array is by default initialized to 0.0 as this is an instance field of the class. According to Oracle:
Each class variable, instance variable, or array component is
initialized with a default value when it is created.
For type double, the default value is positive zero, that is, 0.0d.
Also, change your TestMatrix(int rows, int cols, double[] data) constructor to:
// declare with a large size
double data[][] = new double[80][80];
public TestMatrix(int rows, int cols, double[] data) {
super();
this.rows = rows;
this.cols = cols;
for (int i = 0, k = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] = data[k++];
}
}
}
Better practice would be making the fields private and write getter and setter methods for those fields.
Either declare matrix to 2*2 as said by Chris
or change
for (int i = 0; i < data.length ; i++) {
for (int j = 0; j < data.length ; j++) {
to
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
If you want any size of matrix upto 4*4 use second solution.
You probably want something like this;
public class Matrix {
public final double[][] values;
public final int rows;
public final int cols;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
values = new double[rows][cols]; // Automatically 0.0.
}
public void print() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.printf(" %6f", values[i][j]);
}
System.out.println();
}
}
}
Matrix m = new Matrix(2, 2);
...
rows and cols are redundant, as you already used values.length, and values[0].length.
A few notes:
Use an IDE, your code did not even compile, this is the minimum
effort you should put into any problem.
Declaring the array as double data[][] = new double[4][4]; makes an array that is 4 "boxes" wide and 4 "boxes" tall. each box will hold a data of the type specified, in your case a double which you are setting to 0.0
public class TestMatrix
{
int rows;
int cols;
double data[][] = new double[2][2];
public TestMatrix()
{
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j <= cols; j++)
{
data[i][j] = 0.0;
}
}
}
public void print()
{
for (int i = 0; i < data.length; i++)
{
for (int j = 0; j < data[0].length; j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
In Addition to above answers
i'm getting 4x4 matrix( with all 0's)
If you wanna find difference replace the existing lines with below code
data[i][j] = 1.0;
System.out.print(data[i][j]+" ");
Hope you understand the reason for getting all the 0's
Your class should be like this:
public class Test {
int rows;
int cols;
double data[][] = new double[2][2];
public void print() {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length; j++) {
System.out.print(" "+data[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test m1 = new Test();
m1.print();
}
}
and this part you can delete. You do not need it. This is not an initialization.
public void matrix() {
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++) {
for (int j = 0; j <= cols; j++) {
data[i][j] = 0.0;
}
}
}
I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.
I'm struggling to finish a java exercise, it involves using 2d arrays to dynamically create and display a table based on a command line parameter.
Example:
java table 5
+-+-+-+-+-+
|1|2|3|4|5|
+-+-+-+-+-+
|2|3|4|5|1|
+-+-+-+-+-+
|3|4|5|1|2|
+-+-+-+-+-+
|4|5|1|2|3|
+-+-+-+-+-+
|5|1|2|3|4|
+-+-+-+-+-+
What i have done so far:
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
String[][] table = new String[num*2+1][num];
int[] numbers = new int[num];
int temp = 0;
for(int i=0; i<numbers.length; i++)
numbers[i] = i+1;
// wrong
for(int i=0; i<table.length; i++){
for(int j=0; j<num;j++){
if(i%2!=0){
temp=numbers[0];
for(int k=1; k<numbers.length; k++){
numbers[k-1]=numbers[k];
}
numbers[numbers.length-1]=temp;
for(int l=0; l<numbers.length; l++){
table[i][j] = "|"+numbers[l];
}
}
else
table[i][j] = "+-";
}
}
for(int i=0; i<table.length; i++){
for(int j=0; j<num; j++)
System.out.print(table[i][j]);
if(i%2==0)
System.out.print("+");
else
System.out.print("|");
System.out.println();}
}
This doesn't work, since it prints 1|2|3|4 in every row, which isn't what I need. I found the issue, and it's because the first for loop changes the array order more times than needed and basically it returns as it was at the beginning.
I know that probably there's a way to achieve this by writing more code, but I always tend to nest as much as possible to "optimize" the code while I write it, so that's why I tried solving this exercise by using less variables and loops as possible.
You are too complex. Hard to find your error. Straight code follows:
public static void main(String[] args) {
//int num = Integer.parseInt(args[0]);
int num = 5; // for test
// creating 2d array
int[][] figures = new int[num][num];
// filling the array
for(int row=0; row<figures.length; ++row) {
for(int col=0; col<figures[row].length; ++col) {
figures[row][col] = (row + col) % num + 1;
}
}
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing border
for(int col=0; col<figures[row].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
// printing data row
System.out.print("|");
for(int col=0; col<figures[row].length; ++col) {
System.out.print(figures[row][col]);
System.out.print("|");
}
System.out.println();
}
// printing final border
for(int col=0; col<figures[0].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
}
public static void main(String args[]){
int dimension = Integer.valueOf(args[0]);
int[][] twoDimArray = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
System.out.print("|"+((i+1)%(dimension+1)));
} //end of j loop
} //end of i loop
} //end of main
The above is only the logic for printing the numbers in the specified sequence.
The other design pattern ( +-+ ) thing i guess u can manage.
the following codes will initialize a 2d int array for the data (1-5 in your example). and print the table. note that the table structure was not save in a String 2d-array. just print the table out. see comments in line.
public static void main(String[] args){
final int num = 5; //hardcoded 5, just for testing.
final int[][] data = new int[num][num];
for (int r = 0; r < data.length; r++) {
for (int c = 0; c < data[r].length; c++) {
final int t = r + c + 1;
data[r][c] = t <= num ? t : t - num;
}
}
// now we have all int data in data 2D-array
// here is the +-+- line
final StringBuilder sb = new StringBuilder("+");
for (int i = 0; i < data.length; i++)
sb.append("-+");
// now print the table
for (int r = 0; r < data.length; r++) {
System.out.println(sb.toString());
for (int c = 0; c < data.length; c++)
System.out.print("|" + data[r][c]);
System.out.println("|");
}
System.out.println(sb.toString());
}
output:
if you give num=9 as argument. the codes above will print:
+-+-+-+-+-+-+-+-+-+
|1|2|3|4|5|6|7|8|9|
+-+-+-+-+-+-+-+-+-+
|2|3|4|5|6|7|8|9|1|
+-+-+-+-+-+-+-+-+-+
|3|4|5|6|7|8|9|1|2|
+-+-+-+-+-+-+-+-+-+
|4|5|6|7|8|9|1|2|3|
+-+-+-+-+-+-+-+-+-+
|5|6|7|8|9|1|2|3|4|
+-+-+-+-+-+-+-+-+-+
|6|7|8|9|1|2|3|4|5|
+-+-+-+-+-+-+-+-+-+
|7|8|9|1|2|3|4|5|6|
+-+-+-+-+-+-+-+-+-+
|8|9|1|2|3|4|5|6|7|
+-+-+-+-+-+-+-+-+-+
|9|1|2|3|4|5|6|7|8|
+-+-+-+-+-+-+-+-+-+
you have make it more complicated try this Simple code :
enter code here
public static void main(String[] args)
{
int n = 5 ;
for(int i = 1 ; i <= n ;i++)
{
for(int l = 0 ; l < n;l++)
System.out.print("+-");
System.out.print("\n|");
for(int j = i ; j <=n;j++ )
{
System.out.print(j+"|");
}
for(int k = 1 ; i >= 2 && k <=i-1;k++)
{
System.out.print(k+"|");
}
System.out.println();
}
}