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;
}
}
}
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'm working on a test prep program. Its not homework or for a grade, I just need help finishing and fixing it so I can study and better understand how it works. The directions are "Write a program named Matrix1.java that randonly fills in 0s and 1s into an n-by-n matrix, prints the matrix." I'm still pretty new to coding so any help would be greatly appreciated. This is the code I have so far:
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix=new Matrix1(5);
matrix.fill();
matrix.print();
}
public Matrix1(int n){
int[][] matrix = new int[n][n];
}
public void fill(int n){ // randomly fill in 0s and 1s
Random rand = new Random();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
Integer r = rand.nextInt;
matrix[i][j] = Math.abs(r);
}
}
}
public void print(int[][]matrix, int n){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.println(array[i][j]);
}
}
}
}
I ended up confusing myself and I'm not sure how to fix it or continue. I think I'm partially on the right track though.
Your code after fixes.
import java.util.Random;
public class Matrix1 {
private final int[][] matrix;
private final int n;
public Matrix1(int n) {
this.n = n;
this.matrix = new int[n][n];
}
/**
* randomly fill in 0s and 1s
*/
public void fill() {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = rand.nextInt(2);
}
}
}
/**
* print the matrix, each row is printed in a separate line
*/
public void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
}
So changes I've made:
I've changed "matrix" and "n" variables into class fields, so you don't have to pass them through class methods
filling array - it should be just 0/1 not any integer so you can use rand.nextInt(2) with bounds - it gives values less then 2
printing array - you have to print row in one line, then change line
It looks like the right direction, check your main method to set the necessary parameters (size, array and size).
Also set the Random object to only be 0 or 1 (Check the Java class libraries for the answer) I believe you can set a parameter inside the Random.nextInt method.
Also if its required to print it like a double array, change up your printing logic since you are always writing to a new line
Well, I see a few problems, which if fixed might help get you on the right track.
First of all, for the random integer, you'll probably want to use the method from this answer:
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
ThreadLocalRandom.current().nextInt(min, max + 1);
I don't think you need to use Math.abs in this case, as long as you call ThreadLocalRandom.current().nextInt(0, 2).
Second, there are a couple of problems with your printing code. First of all, you should be using matrix[i][j] instead of array[i][j]. Second, you'll want to use System.out.print instead of System.out.println.
It should be something like this:
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.print(matrix[i][j]);
}
System.out.println();
}
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
private int[][] m; //it is easier use a global variable
public Matrix1(int n){
m = new int[n][n];
}
public void fill(){ // randomly fill in 0s and 1s
for(int i = 0; i < m.length; i++){
for(int j = 0; j < m.length; j++){
if (Math.random() > 0.5) {
m[i][j] = 1;
} else {
m[i][j] = 0;
}
}
}
}
public void print(){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< m.length; i++){
for(int j = 0; j<m.length; j++){
System.out.print(m[i][j]); //only use print() for the same row
}
System.out.println("");
}
}
}
I need to create a method within my class to add two 2d arrays together. One is implemented as a parameter in the method, while the other is a class object. I need to make sure the arrays are the same size, and if so, add them together. I keep getting an Array Out of Bounds error. Whats wrong with my code?
// method to add matrices
public int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
if (userArray[row][column] == matrix[row][column]) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
if (userArray[row][column] == matrix[row][column]) is the problem.
Remember that arrays are zero-indexed so the elements are numbered from zero to row - 1. Trying to access row row is guaranteed to throw an ArrayIndexOutOfBoundsException because the last row is at index row - 1.
I'm not sure why you even have this line. If you change row to row - 1 and column to column - 1 then this line checks if the bottom-right values in the two matrices are the same. If they're not then the matrices will not be summed. Is that what you intended to do?
I think this is what you are trying to do :
public class Test {
static int row =3;
static int column =2;
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}};
public static void main(String[] args) {
add(new int[][] {{4,4},{5,5},{6,6}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
//check arrays are of the same size
if ((userArray.length == matrix.length) && (userArray[0].length == matrix[0].length) ) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (column -1)) {
for(int col = 0; col < column; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
}
return addedMatrices;
}
}
or better:
public class Test {
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}, {4,4}};
public static void main(String[] args) {
add(new int[][] {{5,5},{6,6},{7,7},{8,8}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
//check arrays are of the same size
if ((userArray.length != matrix.length) || (userArray[0].length != matrix[0].length) ) {
System.out.println("Error: arrays are not of the same size");
return null;
}
int rows = userArray.length;
int cols = userArray[0].length;
int addedMatrices[][] = new int[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (cols -1)) {
for(int col = 0; col < cols; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
return addedMatrices;
}
}
to make the print out more elegant you could change the for loop to :
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
}
System.out.println(Arrays.toString(addedMatrices[i]));
}
The line if (userArray[row][column] == matrix[row][column]) { should be replaced by a line to check if the dimensions of both matrices are the same (I guess that is what's intended). Assuming they are both rectangular arrays, and non empty:
public class MatrixAdder {
static public int[][] userArray = {{1,2},{3,4},{5,6}};
static public int[][] add(int[][] matrix) {
final int nb_rows1 = matrix.length; // nb rows in matrix
final int nb_cols1 = matrix[0].length; // nb columns in matrix
final int nb_rows2 = userArray.length; // nb rows in userArray
final int nb_cols2 = userArray[0].length; // nb columns in userArray
// this assumes A[0] exists, and A[0].length == A[1].length == ...
// both for matrix and userArray
int addedMatrices[][] = new int[nb_rows1][nb_rows1];
if ((nb_rows1==nb_rows2) && (nb_cols1==nb_cols2)) {
for (int i = 0; i < nb_rows1; ++i) {
for (int j = 0; j < nb_cols1; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
static public void main(String[] args)
{
int[][] mx1 = {{10,100},{20,200},{40,400}};
int [][] mx2 = add(mx1);
}
}
To be more robust, you could check that the dimensions of all sub-arrays are the same. You could also check if the matrix has zero dimension (otherwise array[0] will give an error).
If the dimensions are not the same, the returned matrix is filled with zeroes.
If this is not exactly what you need, it should give you enough hints.
if (userArray[row][column] == matrix[row][column]) {}
This is strange to me, I honestly don't know what the intentions are (Your just comparing the last element of each array).
I would do
if(addedMatrices.length == userArray.length && addedMatrices.length == matrix.length){}.
This is ugly but I don't know anything about userArray or matrix. I am presuming userArray is global. Also do j++ and i++, it has the same end result but it is more of the norm.
public static int[][] copyMatrix(int[][] matrix)
{
for (int i = 0; (i < matrix.length); i++)
{
int[][] duplicateMatrix = new int[matrix.length][matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
hello all, this specific function doesnt seem to work since duplicateMatrix isnt initialized as a variable, but I cant seem to initialize since its being created in the loop, I cant find a way to generate the amount of cells need in a column.
help will be appreciated. thanks.
You should initialize the array before the loops, since you only want to initialize it once.
public static int[][] copyMatrix(int[][] matrix)
{
if (matrix.length < 1) {
return new int[0][0];
}
int[][] duplicateMatrix = new int[matrix.length][matrix[0].length];
for (int i = 0; (i < matrix.length); i++)
{
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
This code assumes that all the rows in your input array have the same number of elements (which is true for matrices).
You can relax this assumption if you remember that a 2-dimentional array is simply an array of arrays :
public static int[][] copyMatrix(int[][] matrix)
{
int[][] duplicateMatrix = new int[matrix.length][];
for (int i = 0; (i < matrix.length); i++)
{
duplicateMatrix[i] = new int[matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
A two-dimensional array is an array of arrays. You must first create the two-dimensional array, and then each one of its element individually:
public static int[][] copyMatrix(int[][] matrix)
{
int[][] duplicateMatrix = new int[matrix.length][];
for (int i = 0; (i < matrix.length); i++)
{
duplicateMatrix[i] = new int[matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
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.