How to construct a two dimentional array in Java? - java

I am stuck in a very simple problem for more then 2 hours. I am trying to create a two dimensional array and fill it with a constructor. However, I couldn't pass this step.
public class Test
{
public State [][] test1= new State[4][3];//
public State test2[][]= new State[4][3];//
public State [][]test3;
public State test4[][];
public class State{
int position;
double reward;
int policy;
}
public Test(){
test1[1][1].position=1; // never worked
test2[1][3].position=2; //never worked
test3=new State[4][3];
test3[1][2].position=3; //never worked
test4=new State[4][3];
test4[2][2].position=4;//never worked
}
}
I am calling above function with following code
Test test= new Test();
Log.e("done","pass"); //I never reach here. the code always stuck on the constructor.

When you create the array :
public State [][] test1 = new State[4][3];
you are creating an array that can hold 4 * 3 State instances, but each position in the array is initialized to null.
You need to assign an instance of State to each position in the array before accessing it. If you don't, you'll get a NullPointerException.
For example :
public Test()
{
test1[1][1] = new State();
test1[1][1].position = 1;
....
}

Related

Using an array in a recursive algorithm to find combinations

The idea is if i am at a certain stair i can either go one step down or two so if am at stair 3 i can go down 1 1 1 or 2 1 for example. My code should print all the possibilities. The error I get is that I can't convert the add function to an array (since the add method is a boolean). What is wrong with this algorithm?
public class Stairs {
public static void staircase (int height ){
ArrayList<Integer> Array = null;
explore (height,Array);
}
public static void explore(int objheight,ArrayList<Integer>Array){
int intialheight = 0;
if (intialheight == objheight){
Array.toString();
}
else{ if (objheight > intialheight ){
explore(objheight-2,Array.add(2));
explore(objheight-1,Array.add(1));
}
}
after your feedback I am getting an empty output
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Stairs {
public static void staircase (int height ){
ArrayList<Integer> Array = new ArrayList<Integer>();
explore (height,Array);
}
public static void explore(int objheight,ArrayList<Integer>Array){
int intialheight = 0;
if (intialheight == objheight){
Array.toString();
}
else{ if (objheight > intialheight ){
Array.add(2);
explore(objheight-2,Array);
Array.add(1);
explore(objheight-1,Array);
}
}}
public static void main (String args[]){
staircase(3);
}
}
The method add(E e) in ArrayList returns true upon appending the element e passed as a parameter to the end of the ArrayList.
Your method, explore(int objHeight, ArrayList<Integer> Array) does not accept a boolean for its second parameter. Yet, in that same method, explore, you are recursively calling explore and passing in a boolean to the method.
The following code should be modified to first invoke the add method of Array and then pass Array to the explore method.
Before:
explore(objheight-2,Array.add(2)); This code is passing parameters int and boolean to the explore method, which is not the parameters it accepts. You should instead attempt the following.
After:
Array.add(2);
explore(objheight-2,Array); This code first adds 2 to the Array and then passes the Array to the explore method without invoking any further methods on the Array object.
You will also need to do this for the next line of code, where you have explore(objheight-1,Array.add(1));.
Edit: Upon further examination of the code, I discovered another (sooner) error that occurs. A NullPointerException will occur each time the program runs:
ArrayList<Integer> Array = null;
explore (height,Array);
Then inside the explore method, different methods on Array are invoked, despite Array always being null:
Array.toString();, Array.add(2) and Array.add(1).
The Array object must be initialized inside of either the staircase or explore methods.
ArrayList<Integer> Array = new ArrayList<Integer>(); or ArrayList<Integer> Array = null;
Array = new ArrayList<Integer>();

How to get the same instance of a class in Java?

Good morning,
I have one little problem.
I created one class named Map(). In this class there in one method that generate an Array. Then i created other two classes (Top and Bottom) that extend Map. Then I created 2 objects. One of Top and one of Bottom. I want to get the same array for the Top's object and for the Bottom's object. Here is the code Source:
public class Map{
public Map(){}
public int [] yTopValues()
{
int [] arrayTopY = new int[100];
for(int i=0;i<100;i++)
arrayTopY[i]=randomInt(-50,50);//it puts in i-th position an int between 50 and -50
return arrayTopY;
}
public int [] yBottomValues()
{
int [] arrayBottomY = yTopValues;
for(int i=0;i<100;i++)
arrayBottomY[i]=arrayBottomY[i]-250;
return arrayBottomY;
}
public int [] xValues()
{
int [] arrayX = new int[100];
for(int i=0;i<100;i++)
arrayX[i]=randomInt(0,50);//it puts in i-th position an int between 0 and 50
return arrayX;
}
//other stuff
}
public class TopMap extends Map{
public TopMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yTopValues,
200)
);
}
public class BottomMap extends Map{
public BottomMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yBottomValues,
200)
);
}
In the View class I created two objects one of TopMap and one of BottomMap then I drew the areas with g2.draw(topMap.area) and g2.draw(bottomMap.area)
I need the 2 polygons to be similar, but both of them are different because the method is executed twice. What should I do?
Thank you very much!!
The class Map does not hold the array. It is local only to the xValues() method. If you want the other classes to get that exact array do this:
/*
* Since this is a variable in the CLASS field, this object will
* be accessible to the child class.
*/
private int[] arrayX = new int[100];
public Map(){
createArrayX(); // This makes sure that the array is created, or else
// every value inside of it will be 0.
}
public void createArrayX(){ // Exact same thing as xValues(), but without the return type
for(int i=0;i<100;i++){
arrayX[i]=randomInt(0,50);
}
}
public int[] getArrayX(){ // The method that gets the array.
return arrayX;
}

Adding to custom linked list causes NullPointerException

So, adding stuff to my custom linked list is causing a NullPointerException, and I cannot, for the life of me, figure out why. The purpose of the program is to simulate a chest of drawers, with a list that has the drawers as nodes. The drawers each have a list that includes household objects as nodes.
Here's the relevant bits of code. The error happens when I create a: new ChestOfDrawers(3); in my UI class:
public class ChestOfDrawers{
private static OwnList chest;
private static int[] parametres;
public ChestOfDrawers (int drawers){
chest = new OwnList();
create();
}
public static void create(){
for (int i = 0; i < parametres.length; i++) {
Object drawer = new Drawer(i, parametres[i]);
chest.add(i, drawer); //This is causing the error
}
}
}
The Drawer class being referred to here is the class for the drawers. It requires int i as an ID and int parametres as drawer capacity. The parametres[] array gets filled before the additions to the list are made and it includes info for drawer capacity. The linked list in the question (OwnList) is functioning 100% correctly as it is part of a provided course material, it's near identical to Java's own. I tested the class in another test class and it worked fine, I've just made a mistake here somewhere. Please help!
The problem is that you are not initializing the parametres array. This field will be null by default. You need to either initialize it where it is declared, or in a static initializer block. Additionally, why are the two fields and the create method static? Those certainly seem like instance state...
Here's a better version:
public final class ChestOfDrawers{
private final OwnList chest = new OwnList();
private final int[] parametres;
public ChestOfDrawers (int drawers){
if (drawers < 0) throw new IllegalArgumentException("Drawers may not be negative");
chest = new OwnList();
parametres = new int[drawers]; // <-- I'm assuming that's the intended meaning
initialize();
}
private void initialize(){
for(int i = 0; i < parametres.length; i++){
Object drawer = new Drawer(i, parametres[i]); // <-- parametres[i] will always be 0
chest.add(i, drawer);
}
}
}
I'm not sure what you need the parametres array to actually contain (a new array of int will be filled with zero values) - but I'll leave that as an exercise to the reader :-)

initialise a array in one class and make accessible to another

this may seem daft i have a class called ship locations which i wish to store all my ships locations, ive extended it from my client class and simply called the set method as follows
sub.local being a multidimensional array from the ship class
sub.local = new int[2][2];
sub.local[0][0] =row;
sub.local[0][1]=col;
sub.local[1][0]=row;
sub.local[1][1] =col+1;
toServer.writeInt(row);
toServer.writeInt(col);
toServer.writeChar('s');
sub.placed=true;
setp1sub(sub.local);
When i print it back through another class it comes back with the location in the memory rather than the numbers i need. What is the reason for this
public class ShipLocations {
static int [][] p1sub;
public ShipLocations()
{
p1sub = new int[2][2];
}
public int[][] getp1sub()
{
return p1sub;
}
public void setp1sub(int[][] local) {
for (int i = 0;i <local.length;i++)
{
for(int j = 0;j<local.length;j++)
{
p1sub [i][j]= local[i][j];
}
}
}
}
would it be that im passing it as sub.local ?
output is [[I#a401c2
Instead of writing
System.out.println(yourArray);
use
// for multidemensional arrays:
System.out.println(Arrays.deepToString(yourArray));
// or for one dimemsional arrays:
System.out.println(Arrays.toString(yourArray));
Here is a link to the relevant JavaDoc.
For an explanation of your output, you can look at this answer.

How come the array of objects I'm creating is a set of nulls?

So I'm creating a class called dicegame. Here's the constructor.
public class dicegame {
private static int a, b, winner;
public dicegame()
{
a = 0;
b = 0;
winner = 2;
}
And now in the main, I'm creating an array of this object (I called it spaghetti for fun).
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[10];
spaghetti[1].roll();
}
But when I try to do anything to an element in the array, I'm getting the NullPointerException. When I tried to print one of the elements, I got a null.
You created an array, but you have to assign something (e.g. new dicegame()) to each element of the array.
My Java is slightly rusty, but this should be close:
for (int i=0; i<10; i++)
{
spaghetti[i] = new dicegame();
}
new dicegame[10]
just creates an array with 10 empty elements. You still have to put a dicegame in each element:
spaghetti[0] = new dicegame();
spaghetti[1] = new dicegame();
spaghetti[2] = new dicegame();
...
You need spaghetti[1]=new dicegame() before you call roll() on it.
Right now you are allocating an array,but don't. Place any objects in this array, so by default java makes them null.
1.you have just declared the array variable but not created the object yet. try this
2.you should start index with zero not with one.
dicegame[] spaghetti = new dicegame[10]; // created array variable of dicegame
for (int i = 0; i < spaghetti.length; i++) {
spaghetti[i] = new dicegame(); // creating object an assgning to element of spaghetti
spaghetti[i].roll(); // calling roll method.
}
Firstly,you should create object for every spaghetti input of yours.
You can start with whatever value you want. Just be sure that the size of array is matched accordingly so that you won't get ArrayIndexOutOfBounds Exception.
So,if you wanted to start with 1 and have 10 objects of the class dicegame,you will have to assign the size of the array as 11(since it starts from zero).
your main function should be like :
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[11];
//the below two lines create object for every spaghetti item
for(int i=1;i<=11;i++)
spaghetti[i]=new dicegame();
//and now if you want to call the function roll for the first element,just call it
spaghetti[1].roll;
}

Categories

Resources