Create an object and put in an array - java

I want to create just an object,i am not sure if i am creating and it is right.My example ,lets say i have 2 class(Userinput and paper).0fcourse there is and the main.In this example No inherit (just 2 simple class).Am i create an object right?How i put in it in an array or in the same array?
package exercise;
public class Exercise{
static int N; //from keyboard .I have a class userinput.It doesnt need to write it here ,i have in the other class the problem
public static void main(String[] args) { // main class
Paper[] pin = new Paper[N]; //i create an array
Paper.setpencil(3); // i wrote the 3 .In this way i create 3 pencil?
Paper.getpencil(3);
Paper.setsomething(4); // i wrote the 4 .I create 4 ?
Paper.getsomething(4);
} }
public class Paper{ //in this class i am confused
public Paper(){} //default constructor
private int pencil;
private String something;
public int getpencil(){
return pencil;
}
public void setpencil(){
pencil=UserInput.getInteger():
}
public int getsomething(){
return something;
}
public void setsomething(){
something=UserInput.setInteger();
}
}

with this statement:
Paper[] pin = new Paper[N];
you create an array of object of class Paper.
You must also create an object for each array element like:
for (int i=0; i < N, i++)
{
pin[i] = new Paper();
}
And next you should refer to an element (e.g. first element that with index 0) of the array in this way:
pin[0].setpencil(3);

Related

Java - Custom type nested in class

I am once again asking for technical support.
I need to define a custom type inside a class, I've done it like this:
public class MainClass {
private class CustomType {
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
private CustomType[] myArray;
public MainClass() {
myArray = new CustomType[1024]
System.out.println(this.CustomType[0].varB);
}
}
When I run it throws a NullPointerException at System.out.println(this.CustomType[0].varB);
I've tested if myArray gets properly initialized with 1024 elements and it does, however I can't seem to access them.
I just moved from C++ to Java so I'm still getting used to it, am I missing something blatant?.
You only create an array without any objects, so this.CustomType[0] is null.
You should add the objects to the array:
public MainClass() {
myArray = new CustomType[1024]
for (int i =0; i<myArray.length;i++ {
myArray[i] = new CustomType();
}
System.out.println(this.myArray[0].varB);
}
Also you should make the member of CustomType private and access it via getter and setter.
Two things,
You must instantiate CustomType.
CustomType does not need access to MainClass.this so you can make it static.
So
public class MainClass {
private static class CustomType {
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
private CustomType[] myArray;
public MainClass() {
myArray = new CustomType[1024];
for (int i = 0; i < myArray.length; ++i) {
this.CustomType[i] = new CustomType();
}
// Or
Arrays.setAll(myArray, CustomType::new);
System.out.println(this.CustomType[0].varB);
}
}
Not making it static stores a MainClass.this in every CustomType instance which is unnecessary overhead.
Arrays in java are objects. The following line of the code you posted creates an array of 1024 elements where each and every element is null.
myArray = new CustomType[1024];
If you want to place actual objects in the array, named myArray, you need to create instances of class CustomType and assign them to elements of the array, for example:
CustomType instance = new CustomType();
myArray[0] = instance;
Then you can execute the following line of code and it will not throw NullPointerException.
System.out.println(myArray[0].varB);
Here is the full code to get the value of varB. In which you can avoid declaring CustomType[] myArray
public class Test
{
private static class CustomType
{
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
public static void main(String... args)
{
System.out.println(new CustomType().varB);
}
}
The solution is to add some elements to that array. See the below steps for more information.
constructor will be invoked, when you create the object of that class
And then you created an empty array of CustomType with size 1024 and trying to access the first element which does not exist(default is null) and trying to perform operations on that null reference. So you are getting the NullPointerException.

Calling an array from a different class - Java

How can I access my array from a different class? I have 3 classes; Main (where I want to access the array from) FramePanel (my GUI and where the value from UserInputNum is taken from) and StoryArray (where my array is saved).
I need to access the array in the nested If loop in the Main class, this is because I want too save the specific array data to a string and eventually append it into a JTextArea.
Here are the two classes needed:
Main.java
public class Main
{
public static String UserInput;
public static int UserInputNum;
public static void main(String[] args)
{
FramePanel.main();
StoryArray.main();
UserInputNum = Integer.parseInt(UserInput);
if (UserInputNum >= 0)
{
if (UserInputNum <= 399)
{
StoryArray.storyLine[UserInputNum];
}
else
{
}
}
else
{
}
}
}
StoryArray.java
public class StoryArray
{
public static String storyLine[] = null ;
public String[] getStoryLine()
{
return storyLine;
}
public static void main()
{
//String[] storyLine;
storyLine = new String[399];
storyLine[0] ("1")
storyLine[1] ("2")
storyLine[2] ("3")
storyLine[3] ("4")
storyLine[4] ("5")
storyLine[5] ("6")
In another class you can call the array like this:
String value = StoryArray.storyLine[index];
As it is a static public field you can access it directly by StoryArray.storyLine. But as you have a getter ethod I would suggest to make this getter setter static and the array field private and access it through getter method like that: StoryArray.getStoryLine() (to see why read about encapsulation).
You also shouldn't start your class (main) name from lower case, here are standard coding conventions for java language: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
Once you've called StoryArray.main(), then you should be able to do StoryArray.storyLine[/*element id*/] = "whatever you want" to get or set any element in storyLine. Additionally, you aren't defining any default array values. In StoryArray.main(), you need to have lines of the form storyLine[n] = "n".

The object override the previous one for the object array

For the main function, I try to build some object all_data[] from 0 to 4, but when the statement System.out.println(all_data[0].getName());
they will output the most updated one (apple,orange,water,coke,Banana)
, not "apple".
public class food_data {
public static int food_drink; //1=food,2=drink
public static String name;
public static food_data[] all_data = new food_data[1000];
public food_data(int food_drink, String name) {
this.food_drink=food_drink;
this.name=name;
}
public int getFoodDrink()
{
return this.food_drink;
}
public String getName()
{
return this.name;
}
public static void main()
{
all_data[0]= new food_data(1,"apple");
System.out.println(all_data[0].getName());
all_data[1]= new food_data(1,"orange");
System.out.println(all_data[0].getName());
all_data[2]= new food_data(0,"water");
System.out.println(all_data[0].getName());
all_data[3]= new food_data(0,"coke");
System.out.println(all_data[0].getName());
all_data[4]= new food_data(1,"Banana");
System.out.println(all_data[0].getName());
}
}
How can I solve this problem?
Thank you!
change your main method as
public static void main()
{
all_data[0]= new food_data(1,"apple");
all_data[1]= new food_data(1,"orange");
all_data[2]= new food_data(0,"water");
all_data[3]= new food_data(0,"coke");
all_data[4]= new food_data(1,"Banana");
for(int i=0; i< all_data.length; i++)
{
if( null != all_data[i])
{
System.out.println(all_data[i].getName());
}
}
}
you need to put data in array all_data then create loop and iterate over array. print array's element at each index.
In every System.out.println you call all_data[0], which of course prints out always the same object. Just increment the index here the same as you do for the assignments.
Edit: Ok, now i see the problem. You made all fields in the class food_data as static, which means, they are not object specific. Remove the static keyword, then the program should work correctly.

How do I correctly instantiate a public class+data structure in a class so that other objects can use it?

In my code, I have a seperate Runner class that instantiates a World, which has a 4x4 array of Locations (a separate class) stored as a Location[][] array. When I print/try to use the Location array, its value is null, and it throws a NullPointerException.
public class Runner
{
public static void main(String[] args)
{
...
WumpusWorld test_loc = new WumpusWorld();
System.out.print(test_loc) //This prints an ID for the WumpusWorld object
System.out.print(test_loc.world) //Null value prints here
//I'd like to pass the test_loc.world values to an actor here
...
}
}
The applicable code for the WumpusWorld is as follows:
public class WumpusWorld
{
public Location[][] world;
public WumpusWorld()
{
new WumpusWorld((byte) 4); //this constructor is used
}
...
public WumpusWorld(byte size)
{
this.world = new Location[size][size];
for(byte i = 0; i<size; i++)
{
for(byte j = 0;j<size;j++)
{
world[i][j] = new Location(j,i,true,false,false);
}
//Location instances called in the form world[x][y]
//are error free in constructor
...
}
}
Your problem might be in the way you call public WumpusWorld(byte size) from the default constructor.
Try this:
public WumpusWorld()
{
this((byte) 4);
}
With new in the call, I had uninitialized values in the inner class

Convert ArrayList to Array throws java.lang.ArrayStoreException

i have a method convertToArray() which converts an ArrayList to an array. I want to call this method every time an element is added to the ArrayList.
public class Table extends ArrayList<Row>
{
public String appArray[]; //Array of single applicant details
public String tableArray[][]; //Array of every applicant
/**
* Constructor for objects of class Table
*/
public Table()
{
}
public void addApplicant(Row app)
{
add(app);
convertToArray();
}
public void convertToArray()
{
int x = size();
appArray=toArray(new String[x]);
}
}
When i call the addApplication(Row app) method I get the error: java.lang.ArrayStoreException
So I changed my addApplicant() method to:
public void addApplicant(Row app)
{
add(app);
if (size() != 0)
convertToArray();
}
I get the same error message. Any ideas why? I figured if it checks the ArrayList has elements before converting it the error should not be thrown?
I can provide the full error if needed
ArrayStoreException thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
So,
public Row[] appArray; // Row - because you extend ArrayList<Row>
public void convertToArray()
{
int x = size();
appArray = toArray(new Row[x]);
}

Categories