Understanding constructors and "this" - java

I'm learning constructors and I understand them for the most part, but I must not understand it enough. I also don't understand this fully. But this code below is supposed to use these constructors:
default constructor, which will be used to fill the matrix with random doubles
constructor which takes a File object, which points to a file
containing a matrix,
constructor which takes a string, which contains the name of the file
constructor which takes a value of type Matrix, and makes a copy of it
constructor which takes a 2D array, and copies its values
And some more, along with a static multiply method. I am supposed to use the commands that are found in main. But I don't quite understand how using a String as the only parameter will do the constructor it's told to, and also the other ones like the default constructor that fills the array with random doubles. I think I should be using this more in my code, but I'm not quite sure.
I mainly just need to be able to set a matrix, fill m1 matrix with random doubles, do it again with m2 matrix, and then use the static multiply method to multiply them, then output the resulting matrix. Thank you.
(Just a heads up, I'm using a 3 by 3 matrix, originally I was supposed to set the size of the matrix to the one found in the text file, but I can also specify the size I want, which I am. And sorry for the messy code. It got all jumbled up while I was trying to figure this stuff out, and I'm afraid of altering it further.)
public class Matrix {
double A[][] = new double[3][3]
// Matrix file name
public Matrix(String name) {
this(new File(name));
}
// Matrix random fill
public Matrix() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
this.A[i][j] = (min + Math.random() * (max - min));
}
// Matrix copy
public Matrix(double[][] A) {
private double[][] arrcopy = new double[3][3];
private double[][] array = new double[3][3];
array = A;
for(int i = 0; i < 3; ++i){
for(int j = 0; j < array[i].length; ++j) {
arrcopy[i][j] = array[i][j];
}
}
}
// Set array from text file
public Matrix(File a) {
File f = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(f);
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
double arrayOne[][] = new double[3][3];
while(inputStreamOne.hasNextInt()) {
for(int i = 0; i < 3; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
// Gets array in file from string name
public Matrix(String a) {
String inputOne = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(new File(inputOne));
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
while(inputStreamOne.hasNextInt()){
for(int i = 0; i < size; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
public static multiply
public static void main(String args[]) {
Matrix m = new Matrix("matrix1.txt");
Matrix m2 = new Matrix("matrix2.txt");
Matrix r = Matrix.multiply(m, m2);
r.output(...);
}
}

Within a constructor or a method this refers to the current object. Within a constructor, if you just use a bare this ( which is to say this without a .method after it ) then it refers to another constructor of the same object that has a different type signature.
Constructors, like any function in Java, can be overloaded. Which is to say, because of Java's type system you can have multiple functions that are of the same name so long as they have different type signatures.
class Foo {
public Foo ( String arg ) {
this(arg, "World");
}
public Foo ( String arg1, String arg2 ) {
// do stuff with arg1 and arg2
}
}
In the above example, one constructor takes a single string and the other takes two. Java won't magically know what to do with the data passed into different constructors. What you have to do is write code in each method so that the resulting object is the same. ( Well technically you don't have to do that, but it's good form ( usually overloaded constructors are for setting default values or for the ease of use of other programmers ))

The this keyword refers to the current object in a constructor or a method, i.e. the object whose constructor or method is being called. Within a constructor, you can also use this to call another constructor in the class.
Refer to http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html for a clear explanation from Java Tutorials.

Related

Java class does not recognize indexing

I made a Matrix class in JAVA that consists of a 2D int array with row and column variables. The constructor of the class generates a Matrix of dimensions n x m and I also implemented two methods that print the values of the Matrix and its transpose (getMatrixValues and getTransposedValues).
However, I would like to make a function that takes as input a matrix and returns its transpose, but since this class is not an array I cannot iterate over it using AT[j][i] = A[i][j], if I understand the exception correctly that IntelliJ is returning me ("java: array required, but Matrix found").
Obviously, I could simply use an int[][] class to begin with instead of defining a new class, but since I am new to JAVA and object-oriented programming in general I wondered whether there is not another possibility without discarding my Matrix class?
Here is my code:
import java.util.Random;
import java.util.Arrays;
public class Matrix {
private int n; // rows
private int m; // cols
private int[][] A; // matrix
public static void main(String[] args){
Matrix A = new Matrix(4,4);
A.getMatrixValues();
System.out.println("\n");
A.getTransposedValues();
Matrix AT = transposeMatrix(A);
}
// constructor (randomly generates matrix)
public Matrix(int rows, int cols){
n = rows;
m = cols;
A = new int[rows][cols];
Random r = new Random();
// r.setSeed(1);
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols ; j++)
{
A[i][j] = r.nextInt(10);
}
}
}
// print matrix
public void getMatrixValues(){
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.print("\n");
}
}
// print transposed matrix
public void getTransposedValues(){
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[j][i]+"\t");
}
System.out.print("\n");
}
}
public static Matrix transposeMatrix(Matrix A){
Matrix AT = new Matrix(A.get_n(), A.get_m());
for(int i = 0; i < A.get_n(); i++)
{
for(int j = 0; j < A.get_m(); j++)
{
AT[j][i] = A[i][j];
}
}
return AT;
}
// getters
public int get_n(){
return n;
}
public int get_m(){
return m;
}
}
Preface
What I have noticed only afterwards was, that when creating the transposed matrix, you actually want to create one with m-rows and n-columns.
That means, you have mixed up m and n in transposeMatrix() when instantiating the new object.
That also means that your code -as it is- only works for square matrices. Just create the object like this: new Matrix(matrix.get_m(), matrix.get_n()).
Note: I re-named your variables; see below in section "Solution".
However, since this is not part of you question, I have not fixed it in the code-snippets below.
Scopes
When in every other method, you are in the lexical scope of the object you are in. This allows you to access its fields (like int[][] A).
But when inside transposeMatrix(Matrix A), you are inside the static scope, meaning, not in the scope of an object.
What adds to the confusion is, that your instance-variable is called A, much like the parameter Matrix A of transposeMatrix(). While you were able to access the 2D-array via A, you now access a Matrix-object via A. That is both because we are not in an object anymore, and because the new local variable overrides the access to the similarly named instance-/static-variable (you would have to use this.A or Matrix.A respectively).
Access modifier
When trying to fix your code, you will stumble upon the restriction of the access modifier you used: private.
private int[][] A will make A (your array) only accessible when referenced from inside your object. But when calling transposeMatrix(), we are in a static-context, meaning, not inside your object anymore.
To fix this, can change the access modifier to allow us to access that field from outside the object. To enable this, you can change the modifier to any other option, with the easiest being to just remove it. However, I suggest you to read more about Access Modifier in the official documentation.
Solution
Let's say we removed private from int[][] A. Will the code work?
No. That's because of the confusion I talked about when explaining scopes. To clear up the confusion, let's rename some variables: (Changed int[][] A to int[][] array, Matrix A to Matrix matrix, Matrix AT to Matrix matrixTransposed)
int[][] array; // <-- Notice the removed access modifier!
// ...
public static Matrix transposeMatrix(Matrix matrix){
Matrix matrixTransposed = new Matrix(matrix.get_n(), matrix.get_m());
for (int i = 0; i < matrix.get_n(); i++) {
for(int j = 0; j < matrix.get_m(); j++) {
matrixTransposed[j][i] = matrix[i][j]; // Won't work!
}
}
}
The code above is still faulty. That is -as we can clearly see now- because we are trying to access a Matrix-object as if it was an array. However, we need to access its instance variable. So, instead of accessing the array the wrong way, we add a .array after every Matrix-object where we try to access its array.
public static Matrix transposeMatrix(Matrix matrix){
Matrix matrixTransposed = new Matrix(matrix.get_n(), matrix.get_m());
for (int i = 0; i < matrix.get_n(); i++) {
for(int j = 0; j < matrix.get_m(); j++) {
matrixTransposed.array[j][i] = matrix.array[i][j]; // NOW we are accessing their arrays respectively
}
}
}
Another solution
With changing the access modifier of the array (like we did above), we enable one to not only override the values of the array, but also to override the array itself.
To restrict one from doing so, we can use "Getters and Setters". They are like a middle-man, allowing us to access the array only indirectly, but with that much control over it as we seem necessary.
We can define them simply creating two new methods (hence its name):
public int get(int i, int j) {
return array[i][j];
}
public void set(int i, int j, int value) {
array[i][j] = value;
}
As you see, we simply forward the request to the "middle-man", which handles it accordingly.
Note: We might encounter a Runtime Exception since we are not checking if the fields at the specified indices actually exist. You might want to add some if-statements before accessing them.
By using the getter and setter, we can modify the code to this:
private int[][] array; // We still want to restrict access to 'array'...
// ...
// ...but still allow accessing them, be it indirectly
public int get(int i, int j) {
return array[i][j];
}
public void set(int i, int j, int value) {
array[i][j] = value;
}
// Now using getter and setter
public static Matrix transposeMatrix(Matrix matrix) {
Matrix matrixTransposed = new Matrix(matrix.get_n(), matrix.get_m);
for (int i = 0; i < matrix.get_n(); i++) {
for (int j = 0; j < matrix.get_m; j++) {
matrixTransposed.set(j, i, matrix.get(i, j));
}
}
}
Sidenote
You should also take a look at naming conventions. They are not critical to make your code function, but make reading and understanding (and thus debugging) it a lot easier.
What I think is also good, is to take a look at a style-guide to see how you can make your code more readible with easy tricks, or just to have a consistent style across your code. I enjoy Google's style-guide for Java, however, there are a lot others as well.
And, you don't have to stick to an existing style-guide, you can have your own style, too! But try to be as consistent as possible. That makes it easier for others and yourself in the future when re-reading your code.

Creating a method of type class Matrix to add two matrices

so, I'm supposed to make a matrix using HashMap<Integer,ArrayList<Number>>, where Number is a class who's instance variables are numerator and denominator.
Class Matrix inherits Class Number, which have methods like fillMatrix(), printMatrix(), addMatrix(Matrix,Matrix) and subMatrix(Matrix,Matrix), problem is in those last two methods, i made them but I'm pretty sure they are completely wrong since i get a NullPointerxception, How do i make such methods?
here is the code.
public class Matrix extends Number implements Calculation
{
public static int rows;
public static int cols;
private ArrayList<Number> myArray;
private ArrayList<Double> myArray2;
private ArrayList<Double> myArray3;
private ArrayList<Double> myArray4;
private HashMap <Integer, ArrayList<Number>> hm;
private HashMap <Integer, ArrayList<Double>> hm2;
public Matrix(int r, int c)
{
hm = new HashMap<>();
hm2 = new HashMap<>();
rows = r;
cols = c;
}
public void fillMatrix()
{
Scanner input = new Scanner(System.in);
myArray = new ArrayList<>();
myArray2 = new ArrayList<>();
System.out.println("Enter the number of rows");
rows = input.nextInt();
System.out.println("Enter the number of columns");
cols = input.nextInt();
Number n = new Number();
for (int i = 0; i < cols;i++)
{
n.setNumerator(i);
n.setDenominator(i+1);
myArray.add(new Number(i,i+1));
double xn = n.getNumerator();
double xd = n.getDenominator();
myArray2.add(xn/xd);
}
for (int i = 0; i < rows; i++)
hm2.put(rows,myArray2);
}
public void printMatrix()
{
for (int i = 0; i < rows; i++)
{hm.put(rows,myArray);
System.out.println(myArray3.toString());
}
}
public Number getItem(int rowNO,int colNO)
{
rows = rowNO - 1;
cols = colNO - 1;
hm.get(rows);
return myArray.get(cols);
}
public void addMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sum = a1+a2;
myArray3 = new ArrayList<>();
myArray3.add(sum);
}
x1=a;
x2=b;
}
}
public void subMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
{ x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sub = a1-a2;
myArray4 = new ArrayList<>();
myArray4.add(sub);
}
x1=a;
x2=b;
}
}
}
}
I'm a bit confused here, so I'll point out some things I noticed.
First off it's difficult to understand your code because of the variable names.
Also none of the methods are static, so i don't really understand why you're bringing in two Matrices for the calculation, then setting them equal to the first two you create in the beggining of both methods.
Next, you have two brackets after your for loop in the subtraction method, I'm guessing it was just a typo when pasting in StackOverflow.
The myArray objects you're adding the sum too is not going to be accumulating all the sums because you are creating a new arraylist each time that loop goes through. Create it outside the loop.
The NullPointerException could be anywhere really, it's hard to tell because the code is a bit confusing.
I would recommend using the LWJGL library which has has classes like Matrix4fand methods like Matrix4f.add();which will help you accomplish this.
Try running your program in debug mode so you can understand which statement gives you null pointer exception.
And I've noticed you have your rows and columns as static but you can change change them within constructor. It seems there is a logical mistake there. These two may be the cause of your exception if you didn't ever give initial value of them before.
If your matrixes can have different rows and columns then you definitely shouldn't use static for them.
To actually understand where nullpointerexception is given, you should also write your main code. But like I said, in debug mode, you can also see it yourself.

Convert matlab to java

i am new in java programming.I need to convert my matlab code to basic java codes not complex like just using loops and array, i tried several times but i failed.Thanks for helping.Here is my code.
x = [1,2,3,4,5,6,7];
x = perms(x);
i = 0;
c=1;
for m=1:1:5040;
for n=1:1:6;
if(x(c,n) == (x(c,(n+1))-1))
i = i+1;
break
end
end
c=c+1;
end
Answer : 2119
Let us go through the Matlab code and translate each row into Java. We will be going to need some abstractions, which we will introduce on the go.
First line:
x = [1,2,3,4,5,6,7];
A vector is assigned to a variable x. We could simply say that a vector is an array of integers, but maybe we need some better abstractions later. Let us define a new class Vector. Do not confuse it with java.util.Vector: There may be multiple classes of the same unqualified name.
class Vector {
private int[] value;
Vector(int... value) {
this.value = value;
}
int apply(int i) {
return value[i - 1];
}
int length() {
return value.length;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (int entry : value) {
result.append(prefix).append(entry);
prefix = " ";
}
return result.toString();
}
}
We are using an array of integers for the internal representation of our Vector. Note that you can swap out the internal representation any time as long as it does not leak out into the classe's interface. Hence, we restrict the access of our value-member to private, meaning only objects of type Vector are allowed to access it.
New Vector objects are instantiated by calling the constructor Vector(int... value), which takes a vararg integer argument. Internally in Java, varargs are the same as arrays, but they give us syntactic sugar, to instantiate our x in the following way:
Vector x = new Vector(1, 2, 3, 4, 5, 6, 7);
which looks very similar to your Matlab code.
An other thing is that, in Java, arrays are zero-indexed, while Matlab starts indexing at 1. Our Vector class defines an apply-method, which is supposed to access the i-th index. Hence, it returns value[i-1].
Now we want to compute
x = perms(x);
perms returns a matrix, containing all permutations of vector x. So we need an other abstraction: Matrix.
class Matrix {
private Vector[] rows;
Matrix(Vector... value) {
this.rows = value;
}
int apply(int x, int y) {
return rows[x - 1].apply(y);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (Vector row : rows) {
result.append(prefix).append(row.toString());
prefix = System.lineSeparator();
}
return result.toString();
}
}
Matrix is defined very similar to Vector, but its internal representation is an array of Vector, the rows of the matrix. Again, we define a method apply to retrieve an element: this time, it takes two parameters, the row index and the column index.
Side note: It is always good to override the method toString which is defined in the top element of Java's type hierarchy: Object. You can try to instantiate a Vector or a Matrix and pass it as argument to System.out.println to see how the string representation looks like.
Now we still need to implement perms in Java. The method perms takes a Vector and returns a Matrix. I have a very hacked and ugly implementation which I am a bit reluctant to show, but for the sake of a complete answer, here it is:
static Matrix perms(Vector vector) {
int[] indices = new int[vector.length()];
for (int i = 0; i < vector.length(); i++)
indices[i] = i;
List<int[]> allPermuationIndices = new ArrayList<int[]>();
permutation(new int[0], indices, allPermuationIndices);
Vector[] perms = new Vector[allPermuationIndices.size()];
for (int i = 0; i < perms.length; i++) {
int[] permutationIndices = allPermuationIndices.get(i);
int[] vectorValue = new int[permutationIndices.length];
for (int j = 0; j < permutationIndices.length; j++)
vectorValue[j] = vector.apply(permutationIndices[j] + 1);
perms[i] = new Vector(vectorValue);
}
return new Matrix(perms);
}
private static void permutation(int[] prefix, int[] remaining, List<int[]> returnValue) {
if (remaining.length == 0)
returnValue.add(prefix);
else {
for (int i = 0; i < remaining.length; i++) {
int elem = remaining[i];
int[] newPrefix = Arrays.copyOf(prefix, prefix.length + 1);
newPrefix[prefix.length] = elem;
int[] newRemaining = new int[remaining.length - 1];
System.arraycopy(remaining, 0, newRemaining, 0, i);
System.arraycopy(remaining, i + 1, newRemaining, i + 1 - 1, remaining.length - (i + 1));
permutation(newPrefix, newRemaining, returnValue);
}
}
}
Don't bother to understand what it is doing. Try writing a clean implementation on your own (or google for a solution).
Now, if we want to reassign our x, we run into trouble: The type does not match: We declared x to be of type Vector, but perm is returning a Matrix. There are multiple ways to solve this:
We could declare Vector to be a Matrix, i.e., change the signature to Vector extends Matrix. This solution may make sense, but be careful not to break behavioral subtyping: If a class B is a class A, then B must have the same behavior as A and can define additional behavior. Look up the Liskov Substitution Principle on the same note.
We could declare x to be of a supertype of both, Vector and Matrix. Currently, this is Object, but we could also define a new common supertype. This solution may however lose our static type safety. For example, if we want to use x as argument to perm, we need to dynamically cast it to a Vector
We could define a second variable x2 of type Matrix which holds the result. I suggest this solution in this case.
Next, we assign i = 0; and c=1;, which in Java translates to
int i = 0;
int c = 1;
Now, the for-loops:
for m = 1:1:5040
...
end
translates to
for (int m = 1; m <= 5040; i++) {
...
}
The only thing remaining, besides putting it all together, is the if-statement:
if(x2(c,n) == (x2(c,(n+1))-1))
...
end
translates to
if (x2.apply(c, n) == (x2.apply(c, n+1) - 1)) {
...
}
where apply is the method we defined on Matrix. Note that in Java, == will give you strange results if applied to non-primitive types, i.e., everything besides int, byte, char, double, boolean, and float. Generally, you test equivalence using the method equals which is defined on Object.

Initializing a three dimensional array of arraylist in Java

I have a multidimentional array, as:
private static ArrayList [] [] pVTable = new ArrayList [35] [12];
My first try to initialize it was:
for (ArrayList[] x : pVTable) {
for (ArrayList y : x) {
y = new ArrayList<TableValue>();
}
}
which didn't work.
I ended up doing it more manually, as in:
for ( int i = 0; i < pVTable.length; i++) {
for ( int j = 0; j < pVTable[0].length; j++) {
pVTable [i] [j] = new ArrayList<TableValue>();
}
}
which works fine.
Although I have a solution, I was wondering why the first (more elegant) piece of code doesn't do the same job?
In the first snippet, if we strip away the syntactic sugar of the foreach operator (:), the code translates to:
for (int xIndex = 0; xIndex < pVTable.length; xIndex++) {
ArrayList[] x = pVTable[xIndex];
for (int yIndex = 0; yIndex < x.length; yIndex++) {
ArrayList y = x[yIndex];
y = new ArrayList<TableValue>();
}
}
As you can see, nothing is ever assigned to the actual array – only to the temporary y variable.
In the first example your code although modifies y does not change x.
You are mixing ArrayList (part of collections api) with Arrays, which is rather confusing (for me anyway)
I would suggest something like this instead :
List<Point> myShape = new ArrayList<Point>;
Where point contains two ints representing X and Y.
The scope of the first is incorrect. y is just a placeholder variable. Changing that doesn't change the underlying object, just the object that y refers to. You can see the same problem in the following code snippet:
public static int x = 2;
public static void foo(int y) {
y = 3;//does nothing outside of foo
}
public static void main(String[] args) {
System.out.println(x);//prints 2
foo(x);
System.out.println(x);//prints 2, x hasn't changed.
}

Returning an Array

I am new to programming and Java and trying to write a program which takes two arrays as input and reports back their sum. I want to do this by creating a class which takes two arrays as constructor inputs and then creating a method that adds them together and a method which prints out this new sum array.
Here is my class:
public class test1 {
int [] a;
int [] b;
int [] final23;
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[0]);
}
}
}
Here is my main class:
public class main1 {
public static void main(String[] args)
{
int l[] = {4,7,2};
int k[] = {4,6,2};
test1 X = new test1(k,l);
X.sum(k,l);
X.print();
}
}
I keep getting an error when I run this through:
Exception in thread "main" java.lang.NullPointerException
at test2.sum(test2.java:17)
at main1.main(main1.java:8)
I guess what I really want is for my sum method to take a test1 object as input. However, I don't know how to do this.
Your variable final23 is never initialized.
In java you have to initialize an array before using it. Either you do it during the declaration (like you did with k and l) or you have to do it later with a new arrayType[arraySize];
Here are the way an array can be declared/initialized.
int[] iArray = {1, 2, 3}; //Declaration, Initialization, set values
int[] iArray; //Declaration
iArray = new int[3]; //Initialization
iArray[0] = 1; //Set value
int[] iArray; //Declaration
iArray = new Array[3]{1, 2, 3}; // Initialization and set values
You can of course for the two last sample put the initialization on the same line that the declaration.
Try this (cleaned) code :
public class test1 {
int[] final23;
public int[] sum(int[] x, int[] y) {
final23 = new int[Math.min(x.length, y.length)];
for (int i = 0; i < final23.length; i++) {
final23[i] = x[i] + y[i];
}
return final23;
}
public void print() {
for (int aFinal23 : final23) {
System.out.println(aFinal23);
}
}
public static void main(String[] args) {
int l[] = {4, 7, 2};
int k[] = {4, 6, 2};
test1 x = new test1();
x.sum(k, l);
x.print();
}
}
Resources :
Oracle.com - Arrays
JLS - Array Initializers
JLS - Array Creation Expressions
I'm going to take a long shot here
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
As a side comment, I'm guessing that you want to add all of the elements of the vector, not just the first. Change your for-loop body to:
final23 [i]=x[i] + y[i] ;
What's final23? Where is it created?
Try adding this to your constructor
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
this.final23 = new int[Math.min(a.length, b.length)];
}
Now final23 is defined and created, and you can use it in your class.
If you supply test1 with arrays in the ctor, you don't need them in the sum method, just use the ones you have in the class already:
public int [] sum()
{
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [i]=a[i] + b[i] ;
}
return final23;
}
You also had an error in the sumation, you didn't use the iteration variable, you also need to initialize final23 in the ctor.
You have to initialize final23 array before putting elements in it (on line 17).
**final23 = new int[Math.min(x.length, y.length)];**
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
I see a couple of things to point out here.
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
First of all, remember that each test1 object - that is, each instance of your test1 class - has variables named a and b. I'm guessing that in the constructor, you want to take the arrays x and y which were passed as parameters and store them into a and b of the object. To do that, all you have to do is write
a = x;
b = y;
You don't have to write int[] again, not when you just want to access an existing array-type variable. You only write that when you're creating a new array-type variable. In this case, when Java sees that you've written int[] a in the constructor, it thinks you want to create yet another array-type variable named a, separate from the one in the test instance, and that's the one that gets set equal to x. The thing is, that local variable gets lost at the end of the constructor. So you're left with a test1 instance that has variables a and b that still refer to nothing, i.e. they're null.
By the way, since you're going to be using the array final23 later on, you should initialize it. Right now, it refers to null because you never set it to equal anything else. You'll need to create a new array and store it in that variable in order to be able to use it later on. So put this line in your constructor:
final23 = new int[Math.min(a.length, b.length)];
That creates the new array with a length equal to the shorter of the two arrays passed in.
Moving on:
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
In this bit of code, you have the same issue as in the constructor: you create two new array-type variables a and b that get used instead of the ones in the test1 object. I don't think that's what you meant to do. So I'd say get rid of those last two lines entirely.
There's another problem, though: if you think about it, you still have two arrays stored in the test1 object. Assuming you've fixed your constructor, those are the same two arrays that were passed to the constructor. And now you're getting two new arrays under the names x and y. So you have four arrays total. Which ones did you want to sum up? I'm guessing that you meant to sum the two arrays that were passed to the constructor. In that case, your sum method doesn't need to - and shouldn't - accept more arrays as parameters. Get rid of the parameters x and y, so your sum method just looks like
public int [] sum()
{
Now you have to change the rest of that method to use a and b, starting with the for loop. Change its opening line to this:
for (int i = 0; i < Math.min(a.length, b.length); i++)
{
I notice you were wondering how to get your sum method to take an instance of test1. Well, in a way it actually does. There's a special hidden parameter passed to all methods (except static ones) that contains the object the method was called on - in fact, using your main program as an example you could kind of think of X.sum(k,l); as actually calling test1.sum(X,k,l);, where X is the special hidden parameter. You can access it inside the method using the name this (so you could write this.a instead of just a), but Java is generally smart enough to do that for you.
In the body of the for loop, you have another problem. What you want to do is add up corresponding elements of the arrays, i.e. a[0] + b[0] goes into final23[0], a[1] + b[1] goes into final23[1], and so on. But inside the for loop, you only ever add up element 0 of each array. You need to use the loop index variable i, because that runs through all the values from 0 to the length of the shorter array minus 1.
final23 [i] = a[i] + b[i];
}
return final23;
}
So the first time the loop runs, i will be 0, and you'll set final23[0] = a[0] + b[0]. The next time it runs, i will be 1, and you'll set final23[1] = a[1] + b[1]. And so on.
The same problem occurs in your print method. Each time through the loop, you always print out final23[0], when you really should be printing out final23[i] because i changes each time you go through the loop. Change it to
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[i]);
}
}
At this point your program should be working, I think, but there are still some improvements you could make to its design. For one thing, every time you create an object of test1, you know you're immediately going to call sum on it. So why not just put the summing-up code right into the constructor? That way you know that the sum will be computed right when you create the object, and you don't have to call sum explicitly.
Of course, once you do that, you'll have no way to access the array final23 from your main class - except that if you want to print it, you can call the print method. But what if you want to write a main class that, say, adds up two arrays, and then adds the result to a third array? It'd be nice to have a way to get the result from the test1 instance. So you can add an accessor method, possibly named getFinal23, that just returns the sum array final23.
In practice, this operation of adding two arrays would probably be implemented as a static method. So if you want, you could try starting over, and writing it as a static method. (Remember that a static method is one which doesn't receive a special hidden parameter) Inside the static method, you'd have to create the final23 array, go through the loop to compute the sums, and then return the array you created. You'll need to enclose the static method in a class, of course, but that class doesn't have to have a constructor since you never really use it for anything. It'd look something like this:
public class SumClass { // pun intended ;-)
public static int[] sum(int[] x, int[] y) {
// you fill in this part
}
}

Categories