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.
Related
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
}
I hava a question about array initialization in java.
The code is as below:
public class Sentence {
int size;
int[] words=new int[size];
public Sentence(int size) {
this.size=size;
}
public static void main(String[] args) {
Sentence falseOne = new Sentence(6);
falseOne.words[0] = new int[6];
}
}
The problem shows: Type provided "int[]", but required "int"
Could anyone tell me where is wrong?
The field words for an object of class Sentence is of type int[] i.e. it is an array whose elements must be of integer type. In the second line within the main function, you are trying to initialize the first element of the words array with an integer array, instead of an integer.
Also, you should also create the array itself within the constructor.
The code should look like this:
public class Sentence {
int size;
int[] words;
public Sentence(int size) {
this.size = size;
this.words = new int[size];
}
public static void main(String[] args) {
Sentence falseOne = new Sentence(6);
falseOne.words[0] = 7; //just picked an arbitrary integer to demonstrate what should be initialized
}
}
When I create a two-dimensional array and initialize only one dimension of the array, everything works, but if I call it from another class, nothing works. why?
import java.util.Scanner;
public class Coursework {
public static void main(String[] args) {
int verticalMatrix; // vertical size of Matrix
int horisontMatrix; // horisont
System.out.println("Enter vertical size of Matrix ");
Scanner sc = new Scanner(System.in);
verticalMatrix = sc.nextInt();
int [][] matrix = new int [verticalMatrix][];
}}
This code works, but when I use extends class Matrix I can't save only one size (verticalMatrix). How fix it?
public class Coursework extends Matrix {
public static void main(String[] args) {
int verticalMatrix; // vertical size of Matrix
int horisontMatrix; // horisont
System.out.println("Enter vertical size of Matrix ");
Scanner sc = new Scanner(System.in);
verticalMatrix = sc.nextInt();
int [][] matrix = new int [verticalMatrix][];
Matrix Class
public class Matrix {
public static int [][] Matrix;
public void getSize(){
System.out.println("This method still epmty");
}
}
You have your int array variable called just like your class (Matrix). This does probably not cause an error but it is not preferred. You can pass the vertical length of the array t the constructor, like this:
public class Matrix {
public static int [][] matrix;
public void Matrix(int verticalLength){
this.matrix = new int[verticalLength][];
}
public void getSize(){
System.out.println("This method still epmty");
}
}
import java.util.ArrayList;
public class bugs
{
public ArrayList<Integer> elements1;
public ArrayList<Integer> elements2;
public bugs(ArrayList<Integer> args)
{
elements1 = args;
elements2 = args;
}
public void change(int index, int value)
{
elements1.set(index, value);
}
public void reset()
{
elements1 = elements2;
}
public static void main(String[] a)
{
ArrayList<Integer> stuff = new ArrayList<Integer>();
stuff.add(1);
stuff.add(1);
stuff.add(1);
stuff.add(1);
bugs b = new bugs(stuff);
b.change(2, 999);
b.reset();
System.out.println(b.elements2);
}
}
This outputs:
[1, 1, 999, 1]
The second arraylist elements2 is there to reset the arraylist elements1 to its original position. However, for some reason elements1 is being copied to elements2, printing
[1, 1, 999, 1]
and not
[1, 1, 1, 1]
You are passing the same ArrayList reference to both variables.
What you meant to do is:
public bugs(ArrayList<Integer> args)
{
elements1 = new ArrayList<Integer>(args);
elements2 = new ArrayList<Integer>(args);
}
EDIT:
Note that this is only a temporary fix. Calling reset() will pass the reference of elements2 to elements1 and then you have the same situation. If you create a new arraylist and you pass another list as argument, you create a new reference with the same contents. This means you must also adjust your reset() method to create a new list and pass elements2 as argument.
In java you can pass by reference or by value. If you are using primitive data types, you are passing by value. So:
public void method(int num)
{
int num1 = num;
int num2 = num;
}
This method pass num value to num1 and num2 primitive data types. If you add something to num1 it will not change num2 to the same value. But if you are using non primitive data types like ArrayList:
public bugs(ArrayList<Integer> args)
{
elements1 = args;
elements2 = args;
}
You should expect that change in elements1 array will change elements2 array also. In this example you are passing the same ArrayList reference to both variables.
The solution for your problem is create copy of your arrays:
public bugs(ArrayList<Integer> args)
{
elements1 = new ArrayList<>(args);
elements2 = new ArrayList<>(args);
}
public void reset()
{
elements1 = new ArrayList<>(elements2);
}
I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
This is my main method -
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = methods.createBoard();
userInput = methods.input();
}
}
And this is my methods class -
import java.util.Scanner;
public class methods {
//Create board method
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
//Take a guess method
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes and methods therefore I create lots of them.
You'll have to create a new instance of Main and methods first or alternatively declare the createBoard() and input() methods static.
Here is the code snippet:
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.run();
}
private void run() {
methods me = new methods();
int[] playBoard = me.createBoard();
int userInput = me.input();
}
}
Also, as per the naming convention rules for the class name it should be Methods instead of methods.
You haven't declared the variable playBoard being used inside Main. Did you intend to use board2 instead. I guess you want something like below:
board2 = new methods().createBoard();
userInput = new methods().input();
You need to create an object of class methods, in order to access instance methods.