I want to make a 2D array of Arrays, each filled with another object. What I have so far is:
class CustomCache{
boolean dirty = false;
int age = 0;
String addr;
public CustomCache(boolean a, String b, int c){
dirty = a;
addr = b;
age = c;
}
}
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
Setup[][] array = new Setup[numSets][numBlocks];
for(int i=0; i<numSets; i++){
for(int j=0; j<numBlocks; j++){
array[i][j] = new Setup(wpb);
for(int k=0; k<wpb; k++){
array[i][j].wpbArray[k] = new CustomCache(false, "", 0);
}
}//end inner for
}//end outer loop
I keep getting a
java.lang.ArrayIndexOutOfBoundsException: 0
Which means the array is empty. Any idea of how to fix it?
This is the problem:
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
This line:
CustomCache[] wpbArray = new CustomCache[wpb];
runs before the body of the constructor - while wpb is still 0. You want:
class Setup {
int wpb;
CustomCache[] wpbArray;
public Setup(int a) {
wpb = a;
wpbArray = new CustomCache[wpb];
}
}
(I also suggest changing to more meaningful names, and using private final fields, but that's a different matter.)
Related
This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
Closed 3 months ago.
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
int[] pascal;
char[] Larray;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
im trying to do this code but pascal, keeps returning as null, when I declare it outside the constructor;
ive also tried this...
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
and I get this error
sierpinski.java:8: error: cannot find symbol
System.out.println(String.valueOf(s1.pascal));
^
symbol: variable pascal
location: variable s1 of type sierpinski
1 error
error: compilation failed
saying it cannot find symbol, any solutions and does anyone know how to fix this??
thanks
tried declaring the variable at the top, but I have no clue how to get this to work, any ideas?
Constructors are essentially methods.
sierpinski(int row) { // this is a constructor
this.row = row; // this sets a field.
int[] pascal = new int[row+1]; // this creates a new local variable
// constructor ends, and with it, all local variables GO AWAY
}
You want to declare a field. You already have one (row), and you already set it (this.row = row). If you want pascal to still exist when the constructor ends, it needs to be a field and not a local:
public Sierpinski {
private int row;
private int[] pascal;
public Sierpinski(int row) {
this.row = row;
this.pascal = new int[row];
}
}
I want to pass 4 arrays from a method which is in A class, to a method in B class.
I create an instance of class A in the method which is in class B to get the arrays.
The method in A class is defined as Object[] and I use:
return new Object[]{Array1,Array2,Array3,Array4};
to return the arrays.
In method of B class I get the arrays with an object defined as:
private Object outGeoObj[] = new Object[4];
I am retrieving successfully the arrays, but I want to clear the object before I use it again. I tried:
public void ClearValues(){
if (outGeoObj != null){
outGeoObj = null;
}
else{
System.out.println("Object is null");
}
}
but it doesn't work. Any suggestions?
Minimal Working Example:
Class B:
public class MainFem {
private OutGeoMesh outmesh;
private Object outGeoObj[] = new Object[4]; // [0: Xmpoint, 1: Ympoint, 2: Vec, 3: numpoints]
public MainFem() {
outmesh = new OutGeoMesh();
}
public void ClearValues(){
if (outGeoObj != null){
for(int i = 0; i < outGeoObj.length; i++) {
outGeoObj[i] = null;
}
}
else{
System.out.println("Object is null");
}
} // END Method ClearValues
public void MainStart(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel){
outGeoObj = outmesh.createOutGeomesh(Xpoint, Ypoint, nump, c2, Line, drawPanel);
int temp = (int[][]) outGeoObj[3];
System.out.println(temp[0][0]);
}// End Method MainStart
} // END CLASS MainFem
Class A:
public class OutGeoMesh {
private double Xmpoint[][][] = new double[500][200][20];
private double Ympoint[][][] = new double[500][200][20];
private double Vec[][][] = new double[500][2][20];
private int numpoints[][] = new int[500][20];
public OutGeoMesh() {
// TODO Auto-generated constructor stub
}
public Object[] createOutGeomesh(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel) {
for (int j = 0; j <= c2; j++) {
for (int i = 0; i < nump[j]; i++) {
Vec[i][0][j] = i;
Vec[i][1][j] = i+1;
Xmpoint[i][0][j] = Xpoint[i][j];
Ympoint[i][1][j] = Ypoint[i][j];
numpoints[i][j] = numpoints[i][j] + 1;
} // END FOR i
} // END FOR j
return new Object[]{Xmpoint,Ympoint,Vec,numpoints};
} // END METHOD createOutGeomesh
// ---------------------------------
} // END CLASS OutGeoMesh
You need to do something like this:
Arrays.fill(outGeoObj, null);
The reason that your code doesn't work is because you are only erasing your reference to the array, but other parts of your code are still using that same array. By using Arrays.fill you can erase the contents of the array.
my friend has programmed a Breakout game in java. I know C++, which tranfers relatively well to java.
I had a problem when trying to insert a MultiBall brick.
Here are the relevent bits of my function:
private Balle[] balle;
public BriqueMultiBalle(Balle[] bal) {
super();
balle = bal;
SCORE = 100;
}
public void touched() {
visible = false;
balle[Balle.getNInstance()].makeVisible();
}
I get no error but I found out when debugging that balle corresponds to a null pointer. I tried using these different declarations, however, none of them worked:
1.
public BriqueMultiBalle(Balle[] bal) {
super();
for(int i = 0; i < 6; i++)
{
balle[i] = bal[i];
}
SCORE = 100;
}
2.
public BriqueMultiBalle(Balle[] bal) {
super();
balle = new Balle[](bal);
SCORE = 100;
}
However, these methods do not work.
Thanks,
Ghi102
You are getting a null pointer on balle because you never initialize the array, you leave it as
private Balle[] balle;
Try initializing you code
balle = new Balle[bal.length];
for(int i = 0; i < bal.length; i++){
balle[i] = bal[i];
}
Here's an example I wrote using an int array. Same concept, just apply it to your object.
public static void main(String[] args) throws Exception {
int[] arrayInts;
int[] originalInts = { 1, 2, 3, 4, 5 };
arrayInts = new int[originalInts.length];
for(int i = 0; i < originalInts.length; i++){
arrayInts[i] = originalInts[i];
}
originalInts[0] = 10;
for (int i : arrayInts) {
System.out.println(i);
}
}
This is my homework(assignment). I really hope someone can help me figure out what I did wrong.
When I tried to create an object of State
state = new State(tablesize, tb);
and then tried to make a copy
State st2 = new State(state);
and then tried to modify the data in state
state.placeNumber(1,1,3);
for some reason, the data in st2 is also changed.
Below is the code. I really hope someone can point out where my mistake is.
Thanks
public class State
{
private int arraysize;
private int lastfilledx;
private int lastfilledy;
private int table[][];
//constructor
public State()
{
}
public State(State s)
{
arraysize = s.getsize();
lastfilledx = s.lastindex_x();
lastfilledy = s.lastindex_y();
table = s.gettable();
}
public State(int size, int[][] tb)
{
arraysize = size;
table = new int[size][size];
//copy the initial table which is a 2d array
table = tb;
for (int i = 0 ; i < size; i++)
{
for(int j = 0 ; j < size ; j++)
{
if ( table[i][j] == 1)
{
lastfilledx = i;
lastfilledy =j;
break;
}
}
}
}
public void placeNumber(int i, int j, int nextvalue)
{
lastfilledx = i;
lastfilledy = j;
table[i][j] = nextvalue;
}
public void printoutput()
{
for (int i=0; i < arraysize; i++)
{
for (int j=0; j < arraysize; j++)
System.out.print(" " + table[i][j]);
System.out.println("");
}
System.out.println("last fill " + lastfilledx + " " + lastfilledy);
}
public int[][] gettable()
{
return table;
}
public int getsize()
{
return arraysize;
}
public int lastindex_x()
{
return lastfilledx;
}
public int lastindex_y()
{
return lastfilledy;
}
}
public class Dikuho extends State
{
private static State state;
public static void main(String[] args) {
int tablesize = 3;
int tb[][] = new int[tablesize][tablesize];
/*****HARDCODE the table data***/
for (int i=0; i < tablesize; i++)
for (int j=0; j < tablesize; j++)
tb[i][j] = 0;
//test case for 3x3
tb[2][2] = 1;
tb[0][0] = tablesize*tablesize;
tb[0][1] = 7;
tb[1][0] = 8;
tb[2][1] = 2;
//initialize the state
state = new State(tablesize, tb);
**//Here is where the problem is. I only change the data in state but the data in st2 is also changed. I'm not sure what happen here.**
State st2 = new State(state);
state.placeNumber(1,1,3);
st2.printoutput(); **//These both printout same output which is not correct**
state.printoutput();
}
}
Your copy constructor has made a shallow copy of table 2D array. Both the original object and the copy refer to the same original array, because you assign the array reference from the original to the new object. That's fine for the int values, because the values are copied. But that's not okay for objects, for which references to the obejct are copied.
Instead of just copying the reference to the array...
table = s.gettable();
You'll need to create a new, copied array:
table = new int[arraysize][arraysize];
// 2 nested for loops here to copy the contents
public int[][] gettable()
{
return table;
}
So, both of your state objects are referencing the same array. you need to create a new array for each instance.
I am trying to mommertary use a string and convert it to an int to compare the first first column and all the rows with the all of the numbers within the string typed in. When I type in a number, I get a NullPointerException. The thing is, I don't understand why the compiler is telling me this when I feel like I have declared all my objects properly. please help!
import java.util.ArrayList;
public class Decoder
{
private int[][] zipdecoder;
private ArrayList<Integer> zipcode;
private String finalCode;
private String bars;
private int place;
public Decoder()
{
int[][] zipdecoder = new int[][]{
{1,0,0,0,1,1},
{2,0,0,1,0,1},
{3,0,0,1,1,1},
{4,0,1,0,0,0},
{5,0,1,0,1,1},
{6,0,1,1,0,0},
{7,1,0,0,0,0},
{8,1,0,0,1,1},
{9,1,0,1,0,0},
{0,1,1,0,0,0}
};
zipcode = new ArrayList<Integer>();
}
public void insertToArray(String zip)
{
int count = 0;
for(int i = 1; i<zip.length()+1;i++)
{
String piece = zip.substring(count, i);
int number = Integer.parseInt(piece);
for(int j = 0;j<10;j++)
{
if(number == zipdecoder[j][0]){
for(int a = 1;a<5;a++)
{
zipcode.add(place,zipdecoder[j][a]);
place++;
}
}
count++;
}
}
}
You're not initializing the class member zipdecoder but a new local variable (with the same name) in the constructor.
Change this
int[][] zipdecoder = new int[][]{
to
zipdecoder = new int[][]{
and it should work.