How would i instantiate and pass a 2d array to a method? - java

So in my code i have a constructor that is supposed to take two 2d arrays and a enum of a quadrant i already have set up. I have set up my constructor like this.
public ThreadOperation(int[][] a, int[][] b, Quadrants x){
}
I have instantiated a new object that looks like this
ThreadOperation T1 = new ThreadOperation(int[][],int[][],Quadrants.TopLeft);
i keep getting the error error: '.class' expected.
Im new to programming so i guess im just having trouble trying to figure out how to pass the two 2d arrays over to the constructor without giving me an error. These are just placeholders so i can compile.

check this out , you would need to initialise :-
public class Operation {
public static void main(String[] args) {
int [][]a = new int[2][2];
int [][]b = new int[3][3];
TestMe testMe = new TestMe(a,b,Month.January);
}
}
class TestMe {
int [][] a;
int [][] b;
Month month;
public TestMe(int[][] a, int[][] b, Month month) {
this.a = a;
this.b = b;
this.month = month;
}
}
enum Month {
January
}

Related

How do you access int arrays in java methods

I'm trying to declare a 2D array of integers, set its size in the constructor, and change the array's values in a method. When I compile this , I get "Cannot store to int array because "this.a" is null". I'm not sure what I'm doing wrong.
public class arrays {
int[][] a;
public arrays(){
int[][] a = new int[10][10];
}
public void m(){
a[0][0] = 1;
System.out.println(a[0][0]);
}
public static void main(String[] args){
arrays Ar = new arrays();
Ar.m();
}
}
int[][] a = new int[10][10];
This is a combination of int[][] a; and a = new int[10][10]; - int[][] a; declares a new variable. It has the same name as your field, and thus now two different things, both named a, are in 'scope'; the local variable 'wins' - a = new int[10][10]; creates a new array and then assigns a reference to it to your local variable named a, not to the field named a. The constructor then ends, and all local variables are tossed away, because that's what always happens to local variables once a method/constructor exits: They disappear. In other words, you've created a new array but nothing is referring to; your field named a is not pointing at it because you didn't change that.
Just a = new int[10][10]; will get the job done, as now there is no local variable also named a and thus a now refers to the field you have.
Or, even simpler, get rid of your constructor entirely, and initialize your array as you declare it:
public class Arrays {
int[][] a = new int[10][10];
public void m() {
a[0][0] = 1;
System.out.println(a[0][0]);
}
public static void main(String[] args) {
Arrays ar = new Arrays();
ar.m();
}
}
It is all about scoping.
1- You have a property called int[][] a in your class.
2- You have another int[][] a, which is a local variable in your constructor because you defined another int[][].
So, as #Turing85 said,just remove int[][] type definition inside your constructor and that line should be a = new int[10][10];
Additional information:
When you define another int[][] a in your constructor, there is more than one a. While assigning new int[10][10] to a, the closest one in terms of scope(which is inside the constructor) is used. It may be useful for you to exercise scoping.
You have to declare the size before you are initializing the array
public class CustomArrays {
int[][] a = new int[10][10];
public void m(){
a[0][0] = 1;
System.out.println(a[0][0]);
}
public static void main(String[] args){
CustomArrays Ar = new CustomArrays();
Ar.m();
}
}
or this
public class CustomArrays {
int[][] a = new int[10][10];
CustomArrays() {
a[0][0]=1;
}
public void m(){
System.out.println(a[0][0]);
}
public static void main(String[] args){
CustomArrays Ar = new CustomArrays();
Ar.m();
}
}
and
public class CustomArrays {
int[][] a;
public CustomArrays() {
a = new int[10][10];
a[0][0] = 1;
}
public void m() {
System.out.println(this.a[0][0]);
}
public static void main(String[] args) {
CustomArrays Ar = new CustomArrays();
Ar.m();
}
}
all work.

How to make the array size 6 in the following program by passing it like I did here?

I am practising dynamic coding so I want to create a list for class. I hereby Initialized a list for class and want to create an array with different length for each iteration in list. But It doesnt initialize it like I expected instead its length says 0.
import java.io.*;
import java.util.*;
class testcase
{
int N;
int play []= new int [N];
int villain[]=new int [N];
String status;
}
public class Main {
public static void main(String args[] ) throws Exception {
List<testcase> caseno=new ArrayList<testcase>();
Scanner sc=new Scanner(System.in);
int n1=1;
//int n1=sc.nextInt();
int i,j;
testcase t;
for(i=0;i<n1;i++)
{
int n=6;
//int n=sc.nextInt();
t=new testcase();
t.N=n;
System.out.println(t.N+" "+t.play.length);
}
}
}
The array length should print 6 instead it shows 0
You have to create a parametrized constructor in which you'll pass the value of N and then initilaze the arrays. Like
class testcase // Name should be in PASCAL
{
int N;
int [] play;
int [] villain;
String status;
public testcase (int n) { // Constructor
this.N=n;
play = new int [N];
villain=new int [N];
}
}
And in the main methos you create object like this
int n= . . .;//taking input from user
testcase t=new testcase(n);
You need to write a constructor which does these assignment based on the value passed.
// Implement your constructor something like this
public Testcase(int value) {
this.N = value;
play = new int [value];
// Some more assignment based on the need
}
And after that, you need to create the object instance
int N = 6;
Testcase newTestcase = Testcase(N);
NOTE: Clase name should always start with a capital letter.
Try declaring these variable like N, status, play e.t.c as private. After that assign and access them using getter() and setter().

Return an array and a variable together in main function

I have a function like that
Class Return_two{
public static void main(String args[]){
int b=0;// Declare a variable
int a []= new int[3];// Declare an array [both are return at the end of the user define function fun()]
Return_two r=new Return_two();
int result_store= r.fun(a,b);//where should I store the result meaning is it a normal variable or an array where I store the result?
}
public int [] fun (int[] array,int var)//may be this is not a good Return type to returning an array with a variable so what will be change in return type?
{
for(int counter=0;counter <array.length;counter++)
{ var=var+counter;
}
return( array,var);// Here how could I return this two value in main function?
}
}
Now, here lies my question. I want to return an array with a variable as I written above.But as I know one can return a array or a variable but not both. Or one can return one or more variable make those variable as a array element. But how can one return an array with an variable in main function?
If you want to create multiple values, wrap them in an object.
(I'm not able to come up with a meaningful name from what you have posted)
class Result {
private int[] a;
private int b;
public Result(int[] a, int b) {
this.a = a;
this.b = b;
}
//Getters for the instance variables
public int[] getA() {
return a;
}
public int getB() {
return b;
}
}
At the end of fun
return new Result(array, var);
Some best practices:
Don't declare variable names with same name as a parameter (a in fun)
In the above Result class, better to create copies on the array a to avoid mutations outside the class.
If possible, don't use arrays and use a List (this would give you a lot of flexibility)
EDIT:
Your caller will look like
Return_two r=new Return_two();
Result result = r.fun(a, b);
result.getA();//Do whatever you want to do with the array
result.getB();//Do whatever you want to do with that variable
With your current version of the (modified) code, why do you want to return the array since it is same as what you pass to the fun method? Returning only the computed var will work for you (and hence the return type can simply be int).
You can also achieve what you do in fun in one line
return (array.length * (array.length - 1)) / 2;
Wrap these properties into a object, say
Public class FunModel
{
public int[] a;
public int b;
}
then you can return an instance of `FunModel`.
Or
you can use `Tuples`
------------------
Futher Explanation
------------------
The return type here should be a model.
This model should have all that you want to return as properties.
You can return this model from your method.
public class FunModel
{
public int[] a;
public int b;
public FunModel(int[] a, int b) {
this.a = a;
this.b = b;
}
}
And the method should return a instance of this model.
public class ReturnTwo {
public static void main(String args[]){
int b=0;
int a []= new int[3];
ReturnTwo returnTwo = new ReturnTwo();
FunModel funModel = returnTwo.fun(a,b);
//other processing
}
public FunModel fun (int[] array,int tempVar)
{
FunModel temp = new FunModel(array,tempVar);
for(int counter=0;counter <array.length;counter++)
{
temp.b = temp.b + counter;
}
return temp;// you return the model with different properties
}
}

How to run a method from a different class - JAVA [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to call the toh method from my main class(Driver). When I make the call it gives me a null pointer exception. How can I call the toh method in Hanoi from the driver class? When I combine the classes into one it works fine but I need them to be two separate classes. Also, I included the global variables I am using in both classes is that necessary? Any help is welcome. Thanks!
public class Hanoi {
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println("T"+cycle + " Pillar 1 | Pillar 2 | Pillar 3");
System.out.println("-------------------------------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println("\n");
cycle++;
}
}
Main class(driver):
public class Driver{
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
int num = 0;
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<>();
tower[2] = new Stack<>();
tower[3] = new Stack<>();
/* Accepting number of disks */
while(num <=0){
System.out.println("Enter number of disks(greater than 0):");
num = scan.nextInt();
}
N = num;
Hanoi.toh(num);
}
}
You are initializing your tower array inside your Driver class, however, you have not initialized it in your Hanoi class.
As I said in my comment, please do not write global variables twice, in different classes. This is because the different classes DO NOT share the same global variables. (when we say global variable, we mean that they are global to the Driver class only. To access those variables, use the dot operator)
For example, get rid of the N cycle and tower declarations from your Hanoi class
Then access those variables using the dot operator.
tower would become Driver.tower and N would become Driver.N and so forth.
Note: this only works if your Driver class is static, otherwise you would need to access it as an object attribute.
Try to initialize the tower array, something like this:
public static Stack<Integer>[] tower;
public static void toh( int n )
{
tower = new Stack[n];
for ( int d = 0 ; d < n ; d++ )
{
tower[d]=new Stack<>();
}
delete duplicated static values in a class (either Driver or Hanoi)
then in the class that no longer has the static values and add that class to the beginning of all the missing classes.
Ex:
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public static int MyVar;
public void bMethod(){
++MyVar;
}
}
↓ to ↓
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public void bMethod(){
++A.MyVar;
}
}

How can I swap the values of two ints in the method of Java? [duplicate]

This question already has answers here:
Is it possible to write swap method in Java? [duplicate]
(13 answers)
How to do the equivalent of pass by reference for primitives in Java
(8 answers)
Closed 7 years ago.
In Java, it seems that the primitive data type arguments will pass into the method by value. But what if I want to swap the values of two integers.
public static void main(String[] args){
int a = 1;
int b = 2;
swapvalue(a,b);
System.out.println(a);
System.out.println(b);
}
public static void swapValue(int a, int b){
int c = a;
a = b;
b = c;
}
For example, the code above is aimed to swap the values of a and b. In C++ I can pass into the pointers or references to them but I have no idea about how to do this in Java without pointers. How could I make it?
You can't swap them by passing them to a method.
The closest thing you can do is pass an int[] to the method, and swap the elements of the array :
public static void main(String[] args){
int[] arr = {1,2};
swapValues(arr);
System.out.println(arr[0]);
System.out.println(arr[1]);
}
public static void swapValues(int[] arr){
int c = arr[0];
arr[0] = arr[1];
arr[1] = c;
}
Another alternative is to wrap them with some mutable class :
public class IntHolder
{
private int value;
...
}
public static void main(String[] args){
IntHolder a = new IntHolder(1);
IntHolder b = new IntHolder(2);
swapValue(a,b);
System.out.println(a.getInt());
System.out.println(b.getInt());
}
public static void swapValue(IntHolder a, IntHolder b){
int c = a.getInt();
a.setInt(b.getInt());
b.setInt(c);
}

Categories

Resources