How to print two 2D double arrays? - java

Like from {{1.0,2.0},{3.0,4.0}} and {{0.1,0.2},{0.3,0.4}} to {{1.1,2.2},{3.3,4.4}}. If the two input arrays are different sizes, method should return null.
My code below shows [[D#6d06d69c.
What is wrong with my code?
public class Homework13_1 {
public static double[][] sum(double[][]a,double[][]b){
double[][] newA= new double[a.length][a[0].length];
int c=0;
if ((a.length==b.length)){
for (int i=0;i<a.length;i++){
for(int j=0;j<a[0].length;j++){
newA[i][j]=a[i][j]+b[i][j];
}
}
return newA;
}
else{
return null;
}
}
public static void main(String[] args) {
double[][]x={{1,2,3},{2,3,4}};
double[][]y={{2,3,4},{1,1,1}};
double[][] b = {{1,2,-9,7},{3,4,9.9,1.2}};
System.out.println(sum(x, y));
}
}

Java arrays don't override toString. But there is Arrays.deepToString(Object[]) which says (in part) This method is designed for converting multidimensional arrays to strings. You could change
System.out.println(sum(x, y));
to
System.out.println(Arrays.deepToString(sum(x, y)));

Related

two-dimensional array between classes | java

i have one problem with inheritance. I have 2 classes, (CreateAnArray,TheGame) and now - i have two-dimensional array which is created in 'CreateAnArray' class and i want to use it in 'TheGame' class, but every time i try to do it, it shows me 'null'.
public class TheGame extends CreateAnArray{
public void insert(String k){
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
if(arrayOX[i][j] == k && (arrayOX[i][j] != "x" && arrayOX[i][j] != "y"))
arrayOX[i][j]=k;
System.out.println(arrayOX[i][j]);
}
}
}
And the second class:
public class CreateAnArray {
public String[][] arrayOX = new String[3][3];
public void create(){
int k=1;
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
arrayOX[i][j]=Integer.toString(k++);
}
}
}
public void show(){
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
System.out.print(arrayOX[i][j]);
}
System.out.println();
}
}
I've tried a returning method, creating objects but nothing helps, what should I do?
Don't do this. Have your first class operate normally. When it needs arrayOX, have a function return that array to the first class. Don't extend the class here.
public String[] create(){
String[] arrayOX = new String[3][3];
int k=1;
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
arrayOX[i][j]=Integer.toString(k++);
}
}
return arrayOX;
}
Then, call this function to get arrayOX in the other class.

cannot be resolved to a variable java 101

Newbie code for printing a matrix:
import java.util.*;
import java.io.File;
public class Strings {
public static void main(String[] args){
Strings String1 = new Strings();
int alen =0 ,blen =0;
String a,b;
int [][] matrix = new int[alen+1][blen+1];
System.out.println("Enter String a: ");
Scanner usrip = new Scanner(System.in);
a = usrip.next();
System.out.println("Enter String b: ");
b = usrip.next();
System.out.println("Execute print method: ");
String1.printMatrix();
}//end of main
public void printMatrix(){
for(int i=0;i<alen+1;i++)
{
for(int j=0;i<blen+1;j++)
{
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix
}// End class
Since alen , blen are declared in the class not in a mehtod I thought they were global varaibales. But looks like Its not what I think it is.
The error I get is alen cannot be resolved into a variable same for blen and matrix as well.
Same error when I try to access them like String1.alen as well.
the variables "alen" and "blen" you declared in main() are method-local, that means they are not accessible from printMatrix() method. Make them fields instead by writing:
private int alen;
private int blen;
just below the line public class Strings {
or pass them as arguments to printMatrix() method, as Christian suggested.
You cannot access alen, blen and matrix since they are not declared within the printMatrix() scope (you may want to read about scope in Java), here is one simple solution:
Pass the variables as arguments:
public void printMatrix(int alen, int blen, int[][] matrix){
...
}
and call in the main method:
String1.printMatrix(alen, blen, matrix);
Of course, that this is not necessary, you could just do:
public void printMatrix(int[][] matrix){
for(int i=0;i<matrix.length;i++)
{
for(int j=0;i<matrix[i].length;j++)
{
System.out.print(matrix[i][j]);
}
}
}
It is a bit ugly, but for a beginner, you can do the following:
public class Strings {
public int [][] matrix;
public static void main(String[] args){
Strings String1 = new Strings();
int alen =0 ,blen =0;
String a,b;
String1 = new int[alen+1][blen+1];
...
public void printMatrix(){
for(int i=0;i<matrix.length;i++)
{
for(int j=0;i<matrix[0].length;j++)
{
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix
}// End class
this is one way among many:
public void printMatrix(int[][] matrix){
for(int i=0;i<matrix.length;i++) {
for(int j=0;i<matrix[i].length;j++) {
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix`enter code here
call it like:
String1.printMatrix(matrix);

public int[][] GetArray() Says Illegal start of expression

I'm trying to create a 2D array of an image in Java.
Here's what I have so far:
public int[][] GetArray() { //NetBeans is saying 'Illegal Start of Expression' on this line
getimage data;
getwidth;
getheight;
int[][] array = new int[width][height];
for (loop through width) {
for (loop through height) {
array[q][p] = raster.getSample(p, q, 0);
}
}
return array;
I tried setting the return part to:-
return array[][];
but that produced an error saying cannot find symbol.
I'm relatively new to Java and I really want to get better quickly, if you could help me out, I'd really appreciate it.
If you'd like to return an array, do it like this
return array; // CORRECT
What you are doing is incorrect.
return array[][]; // INCORRECT
Your function should look like this
public class MyClass
{
// main is a method just like GetArray, defined inside class
public static void main(String[] args)
{
// do something
}
// other methods are defined outside main but inside the class.
public int[][] GetArray() {
int width = 5; // change these to your dimensions
int height = 5;
int[][] array = new int[width][height];
int q,p;
for(q=0;q<width;q++)
{
for(p=0;p<height;p++)
{
array[q][p] = raster.getSample(p, q, 0);
}
}
return array;
}
}
when you return an array you should not use
return array[][];
you should not use the square brackets [][] . In the return statement we should not mention the dimensions of the array
instead use
return array; this is the correct way

matrix addition java

I wrote this matrix addition program and I dont know why but I keep getting this two errors on lines 61 and 63 and i dont want to handle the exceptions but just throwing would do
error: unreported exception IOException; must be caught or declared
The code of the program is as follows:
import java.io.*;
class Arr
{
int r,c;
int arr[][];
Arr(int r,int c)
{
this.r=r;
this.c=c;
arr=new int[r][c];
}
int[][] getMatrix()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.println("enter element");
arr[i][j]=Integer.parseInt(br.readLine());
}
}
return arr;
}
int[][] findsum(int a[][],int b[][])
{
int temp[][]=new int[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
temp[i][j]=a[i][j]+b[i][j];
return temp;
}
void putmatrix(int res[][])
{
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.println(res[i][j]+"\t");
}
}
System.out.println();
}
}
class Matrixsum
{
public static void main(String args[])
{
Arr obj1=new Arr(3,3);
Arr obj2=new Arr(3,3);
int x[][],y[][],z[][];
System.out.println("\nEnter matrix 1");
x=obj1.getMatrix();
System.out.println("Enter matrix 2");
y=obj2.getMatrix();
z=obj1.findsum(x,y);
System.out.println("the sum matrix is");
obj2.putmatrix(z);
}
}
Because getMatrix throws IOException which must be caught or declared as thrown by main.
In your case the simplest solution is to declare it on main.
public static void main(String... args) throws IOException
getMatrix() is declared to throw IOException. Calls to getMatrix() in main() can generate IOExceptions, which are required to be caught by the function or rethrown. To solve the problem, you could declare main() to throw IOException.
The design of class Arr is a bit strange. Instead of using two redundant objects obj1 and obj2, you should condense it to one object, say one called arrProcessor. So the calls would look like:
x=arrProcessor.getMatrix();
y=arrProcessor.getMatrix();
z=arrProcessor.findSum(x,y);
arrProcessor.putMatrix(z);
Even better, instead of using arrays, you should wrap the arrays in objects, say in a class called Matrix:
public class Matrix{
int[][] values;
int numRows, numCols;
protected Matrix(){/*...*/}
public static Matrix getMatrix(int nRows, int nCols){/*...*/}
public static Matrix addMatrices(Matrix a, Matrix b) throws Exception {/*...*/}
public void print(){/*...*/}
public void plus(Matrix another) throws Exception {/*...*/}
}
So now the code would look like:
Matrix x,y,z;
x=Matrix.getMatrix(3,3);
y=Matrix.getMatrix(3,3);
z=x.plus(y);
z.print();
hey i would suggest you this one.
http://commons.apache.org/math/userguide/linear.html
If you tired to write your own code with matrix, just download library I developed. It can add, multiply, invert, transpond, calculate determinant and solve linear systems.
please check: Linear Math Library
This is open source you can download the source code too and look how in works.

Help me with this Java code

Question:
matrix m1 = new matrix(); // should produce a matrix of 3*3
matrix m2 = new matrix(5,4); //5*4
matrix m3 = new matrix(m2); //5*4
What should be there in the copy constructor to make a new matrix m3 of the same order as of m2?
public class matrix {
int a[ ][ ];
matrix(){
a = new int[3][3];
}
matrix(int x, int y){
a= new int [x][y];
}
matrix (matrix b1){
//how to use value of x and y here....
}
void show(){
System.out.println(a.length);
for(int i=0;i<a.length;i++){
System.out.print(a[i].length);
}
}
}
public class matrixtest {
public static void main(String [ ] args){
matrix a = new matrix();
matrix b = new matrix(5,4);
matrix c = new matrix (b);
a.show();
b.show();
c.show();
}
}
NOTE: You can not use any extra instance variable except the array a.
Accepted answer: #Chankey: this(b1.a.length,b1.a[0].length); – John
Store the number of rows, and the number of columns in the matrix class, and create getters for them.
public class Matrix {
int[][] a;
int rowNum;
int colNum;
//...
public Matrix(Matrix b) {
a=new int[b.getRowNum()][b.getColNum()];
this.rowNum = b.getRowNum();
this.colNum = b.getColNum();
}
public int getRowNum() {
return this.rowNum;
}
}
You need to get the size of the passed b1 matrix
int x = b1.length;
int y = b1[0].lenght;
and can then use it to construct the final array.
a= new int [x][y];
Use
a =new int[b1.a.length][b1.a[0].length];
But it is not recommended .
you should have some get method , which return
matrix dimension.
This is homework, so I'll give you a hint:
How would you get the lengths of the 2 dimensional matrix (a[][]) of b1? proper methods in the matrix class will help - how would you implement those (getX, getY)?
Also, it is better to redirect the constructors to the most detailed one, for example:
matrix(){
this(3,3); // call the constructor below with parameters 3,3
}
matrix(int x, int y){
a= new int [x][y];
}
This can be the most probable answer without using any other instance variable other then the array itself:
import java.io.*;
class matrix
{
private int arr[][];
public matrix() //Default Constructor
{
this(3,3);
}
public matrix(int r,int c) //Parameterized Constructor
{
arr=new int[r][c];
read();
}
public matrix(matrix m) //Copy Constructor
{
System.out.println("Fetching array...");
int r,c;
r=m.arr.length;
c=m.arr[0].length;
arr=new int [r][c];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=m.arr[i][j];
}
}
}
public void read()
{
int i,j,r,c;
r=arr.length;
c=arr[0].length;
Console con=System.console();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
arr[i][j]=Integer.parseInt(con.readLine());
}
}
}
public void show()
{
int i,j;
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr[0].length;j++)
{
System.out.print(" "+arr[i][j]);
}
System.out.println();
}
}
}

Categories

Resources