The object override the previous one for the object array - java

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.

Related

Instantiate array of objects with a variable

I wrote some classes in Java but when I run the program I receive the error "ArrayIndexOutOfBoundsException", the incriminate class is this:
public class Bank {
private String name;
private int maxbankaccount;
private int activebankaccount;
private String radice = "IT8634";
private Conto[] bankaccount = new Conto[maxbankaccount];
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
}
}
I wrote a tester class to test :
public class TestBank {
public static void main (String[] args) {
Bank b1 = new Bank("Fidelity", 10);
b1.addconto("PROVA");
}
}
Since I didn't seem to have made logical errors using the array I debugged, I realized that in the creation of the array of objects the maxbankaccount variable isn't 10 (value passed in Test) but as default value (0),then I tried passing 10 directly and it works good. Why is not the value 10 of maxbankaccount passed but 0?
private Conto[] bankaccount = new Conto[maxbankaccount];
This initialization takes place before the rest of the constructor runs.
Move it into the constructor:
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
this.bankaccount = new Conto[maxbankaccount];
}
You have indeed made a logical error. The array bankaccount is getting initialized when the class is instantiated and is always 0.
Move it into the constructor and initialize it.
public Bank(String name, int maxbankaccount) {
/* ... */
this.bankaccount = new Conto[maxbankaccount];
}
Further more than the issues that are in the other answers, this
private int activebankaccount;
does not initialize the variable activebankaccount
So in:
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
you are using an uninitialized vale as index of the array bankaccount

Create an object and put in an array

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);

ArrayList and connection different classes

Im pretty new to Java. I'm trying to connect these classes together. The Go class, is the main class, that should end up running the program. According to Eclipse, the program doesn't contain any errors, but while running, the outprint is blank.
The Go class:
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
}
}
The Ansat class:
import java.util.ArrayList;
public class Ansat {
public String navn;
public int alder;
public Ansat(String navn, int alder, ArrayList<Ansat> ansat){
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
}
The Data class:
import java.util.ArrayList;
public class Data {
private ArrayList<Ansat> ansat;
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
public ArrayList<Ansat> getAnsat() {
return ansat;
}
}
Output the contents of ArrayList to console
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
for(Ansat ansat : getAnsat()){
system.out.println(ansat.getNavn(), ansat.getAlder());
}
}
}
I recommend just two modifications for you to get a proper readable output.
Add the following method to your Ansat class
//modify the returned string however you want it to appear
public String toString() {
return navn + " , " + alder;
}
and then add this line in your main method of Go class (last statement)
System.out.println(klasseObject.getAnsat().get(0).toString());
The toString() class that is added to the Ansat is overriding the toString() method for Ansat meaning that it allows you to print the fields of Ansat class the way you want it and whenever you invoke toString() on object of Ansat then it will pretty print it for you such as below:
Hej , 123
You can update the toString() method to print it however you want.
If you wish to have more than one element in your ArrayList then you have to do the following changes (but, I do want state that you are not doing this the right way):
Data klasseObject = new Data();
klasseObject.infoListe();
Data klasseObject2 = new Data();
klasseObject.infoListe();
Data klasseObject3 = new Data();
klasseObject.infoListe();
for(Ansat s: klasseObject.getAnsat())
System.out.println(s.toString());
And this changes to your Data class
public void infoListe(){
if(ansat != null) {
ansat.add(new Ansat("Hej", 123, ansat));
} else {
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
}
If I were to review your code and suggest improvements, then I would do the following changes in your classes (copy/paste the following code Go.java file and run it):
import java.util.ArrayList;
public class Go {
public static void main(String[] args) {
// running below creates an ArrayList<Ansat> that is inside KlasseObject
Data klasseObject = new Data();
// creates one Ansat(Hey,123) and add it to list
klasseObject.setData("Hey", 123);
// creates one Ansat(Raf,555) and add it to list
klasseObject.setData("Raf", 555);
// creates one Ansat(X-men,999) and add it to list
klasseObject.setData("X-men", 999);
//as many classes as you want, it would add them all to the list
//of klasseObject
// now that we set three Ansats, we will retrieve the list and print
// them all
for (Ansat s : klasseObject.getAnsatList())
System.out.println(s.toString());
}
}
class Ansat {
public String navn;
public int alder;
//remove the array list from constructor, not needed
public Ansat(String navn, int alder) {
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
//overrided toString method to pretty-print Ansat object
public String toString() {
return navn + " , " + alder;
}
}
class Data {
private ArrayList<Ansat> ansat;
// added the constructor for Data to initialize Data with empty list
public Data() {
ansat = new ArrayList<Ansat>();
}
//replaced infoListe to setData and added args to it so you can
//pass them from main method
public void setData(String name, int age) {
// every time setData is called a new Ansat is added to list
Ansat a = new Ansat(name, age);
ansat.add(a);
}
public ArrayList<Ansat> getAnsatList() {
return ansat;
}
}
Actually the process what you have followed is perfectly correct,But your getting blank because your not printing the arraylist, hence your getting blank output. Just add the below line and you will see the correct output.
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println(ansat);
}
or in the main function just use it like this...
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
System.out.println(klasseObject.getAnsat());
}
Even iterating over array list will fetch you the output -
for (Ansat ansatLoop : klasseObject.getAnsat()) {
System.out.println(ansatLoop.getAlder() + ":"
+ ansatLoop.getNavn());
}
I hope this would solve your query.
Your code is working Perfectly! It has no
System.out.println();
anywhere in the methods that run.
If you modify the method infoListe() to add a println it will print something out
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println("Element Added to ArrayList");
}

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

How do I pass an array of strings into another method?

My code is like this:
public class Test() {
String [] ArrayA = new String [5]
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0])
}
}
I've tried various methods (No pun intended) but none worked. Thanks for any help I can get!
public class Test {
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
public Test(){ // Your Constructor
method1(arrayA[0]); // Calling the Method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, you can just call new Test();
OR if you want the method to be called from your main class by creating an instance of Test you may write:
public class Test {
public Test(){ // Your Constructor
// method1(arrayA[0]); // Calling the Method // Commenting the method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, create an instance of test in your main class.
Test test = new Test();
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
test.method1(arrayA[0]); // Calling the method
And call your method.
EDIT:
Tip: There's a coding standard that says never start your method and variable in uppercase.
Also, declaring classes doesn't need ().
If we're talking about passing arrays around, why not be neat about it and use the varargs :) You can pass in a single String, multiple String's, or a String[].
// All 3 of the following work!
method1("myText");
method1("myText","more of my text?", "keep going!");
method1(ArrayA);
public void method1(String... myArray){
System.out.println("The first element is " + myArray[0]);
System.out.printl("The entire list of arguments is");
for (String s: myArray){
System.out.println(s);
}
}
try this
private void Test(){
String[] arrayTest = new String[4];
ArrayA(arrayTest[0]);
}
private void ArrayA(String a){
//do whatever with array here
}
Try this Snippet :-
public class Test {
void somemethod()
{
String [] ArrayA = new String [5] ;
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1 (String[] A) {
System.out.println("Here's where I need ArrayA[0]"+A[0]);
}
public static void main(String[] args) {
new Test().somemethod();
}
}
The Class name should never had Test()
I am not sure what you are trying to do. If it is java code(which it seems like) then it is syntactically wrong if you are not using anonymous classes.
If this is a constructor call then the code below:
public class Test1() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0]);
}
}
should be written as this:
public class Test{
public Test() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1(String[] ArrayA){
System.out.println("Here's where I need " + ArrayA[0]);
}
}

Categories