This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 4 years ago.
I'm new in Vector usage in Java , and the problem here is that a Vector is not showing the output expected (Correct output: Pollo - Ercole This code output Ercole - Ercole)
.
Class Dipendente
public class Dipendente
{
private String Id;
void setId(String exId)
{
Id=exId;
}
String getId()
{
return Id;
}
}
Class Azienda
public class Azienda
{
private Vector<Dipendente> Dip = new Vector<Dipendente>();
public static void main(String[] args) throws IOException
{
Azienda az = new Azienda();
az.dip.setId("Pollo");
az.Dip.add(az.dip);
az.dip.setId("Ercole");
az.Dip.add(az.dip);
//io.pf is System.out.println(strOut);
az.io.pf(az.Dip.get(0).getId());
az.io.pf(az.Dip.get(1).getId());
}
}
Correct output: Pollo - Ercole
This code output: Ercole - Ercole
You have to create a new instance of the object. Your code is anyway partial since we don't know what is az.dip. But assuming it is an instance of Dipendente. You need to do something like below for it to work.
Azienda az = new Azienda();
Dipendente dip = new Dipendente();
dip.setId("Pollo");
az.Dip.add(dip);
Dipendente dip = new Dipendente();
dip.setId("Ercole");
az.Dip.add(az.dip);
//io.pf is System.out.println(strOut);
az.io.pf(az.Dip.get(0).getId());
az.io.pf(az.Dip.get(1).getId());
In your answer when you call setId the second time it is changing the value of the object that you were using earlier and hence you see a repeated entry.
Related
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Why do I keep getting only tha last object value in Java ArrayList?
(2 answers)
Closed 4 years ago.
package com.snapfires.pdf;
public class FultonObj {
private String fileNo;
private String parcelId;
private String situs;
public String getFileNo() {
return fileNo;
}
public void setFileNo(String fileNo) {
this.fileNo = fileNo;
}
public String getParcelId() {
return parcelId;
}
public void setParcelId(String parcelId) {
this.parcelId = parcelId;
}
public String getSitus() {
return situs;
}
public void setSitus(String situs) {
this.situs = situs;
}
}
package com.snapfires.pdf;
import java.util.ArrayList;
public class List {
public static void main(String arg[]) {
ArrayList<FultonObj> list = new ArrayList<FultonObj>();
FultonObj fuOb = new FultonObj();
String file1 = "file#1";
String file2 = "file#2";
String file3 = "file#3";
String parcelId1 = "parcelId1";
String parcelId2 = "parcelId2";
String parcelId3 = "parcelId3";
String situs1 = "situs1";
String situs2 = "situs2";
String situs3 = "situs3";
fuOb.setFileNo(file1);
fuOb.setParcelId(parcelId1);
fuOb.setSitus(situs1);
list.add(fuOb);
fuOb.setFileNo(file2);
fuOb.setParcelId(parcelId2);
fuOb.setSitus(situs2);
list.add(fuOb);
fuOb.setFileNo(file3);
fuOb.setParcelId(parcelId3);
fuOb.setSitus(situs3);
list.add(fuOb);
for(int b=0; b<list.size(); b++) {
System.out.println(list.get(b).getFileNo());
System.out.println(list.get(b).getParcelId());
System.out.println(list.get(b).getSitus());
}
}
}
When I run this small program, I am only getting the last object that was added to the List. Although it iterates through the list but the result is that it prints out the last object that was added. e.g.
file#3
parcelId3
situs3
file#3
parcelId3
situs3
file#3
parcelId3
situs3
I want all the objects that were added to the List to be there not just the last object. Could someone let me know why this is not happening?
I don't think creating new FultonObj object each time will solve my issue. Here is why. I am reading a text file where it is possible that one line may have only file# and second line may only have file# and parcelId and third line may have file#, parcelId, situs. Or any combination of file#, parcelId, situs per line. However the order will always be same, meaning you will always have: file#, parcelId, situs. So I need to make sure that fuOb is complete before I add it to ArrayList. If I create multiple fuOb then it is possible that none of the fuOb will be complete, meaning it has file#, parcelId, situs.
Your program should be like this. Everytime you are setting data in fuOb it is overriding the previous data..
FultonObj fuOb1 = new FultonObj();
fuOb1.setFileNo(file1);
fuOb1.setParcelId(parcelId1);
fuOb1.setSitus(situs1);
list.add(fuOb1);
FultonObj fuOb2 = new FultonObj();
fuOb2.setFileNo(file2);
fuOb2.setParcelId(parcelId2);
fuOb2.setSitus(situs2);
list.add(fuOb2);
make three FultonObj not use one
fuOb1.setFileNo(file1);
fuOb1.setParcelId(parcelId1);
fuOb1.setSitus(situs1);
list.add(fuOb1);
fuOb2.setFileNo(file2);
fuOb2.setParcelId(parcelId2);
fuOb2.setSitus(situs2);
list.add(fuOb2);
fuOb3.setFileNo(file3);
fuOb3.setParcelId(parcelId3);
fuOb3.setSitus(situs3);
list.add(fuOb3);
This question already has answers here:
Cyclic reference in java [closed]
(3 answers)
Java classes reference each other
(3 answers)
Closed 5 years ago.
I've got two problems:
First: I'm getting StackOverflowError and I don't know how to fix it
Second: I'm using similar syntax in other projects and there was no problems with StackOverflowError. The second problem is in comments in my code. I want to change value of x in class ChangeValueOfVariable and use it in class DisplayValueOfVariable.
class DisplayValueOfVariable{
ChangeValueOfVariable change = new ChangeValueOfVariable();
public int x = 0;
public void showX(){
System.out.println("Value of x: "+x); //There is still x = 0
}
public void changedX(){
change.changeValue();
System.out.println("Value of x: " +x); // Unfortunately there is still x = 0, but I want here to use changed value
}
}
class ChangeValueOfVariable{
DisplayValueOfVariable disp = new DisplayValueOfVariable();
public void changeValue(){
disp.x++;
System.out.println("Value of x: "+disp.x); // Now x = 1
}
}
class Start{
public static void main(String[] args) {
DisplayValueOfVariable displayValueOfVariable = new DisplayValueOfVariable();
displayValueOfVariable.showX();
displayValueOfVariable.changedX();
}
}
I know, that I can change x in public void changedX(), but if I will have more variables it wouldn't help me in cleaning my code.
Thanks for your help ;)
I know that if I'll make something like this
class DisplayValueOfVariable {
public static void main(String[] args) {
int x = 0;
System.out.println(x);
x++;
System.out.println(x);
}
}
It will be my expected result, ok.
I understand that if I will use only one class(which I attached), my code would compile without errors and code would be simpler.
Unfortunately I have to split my code and save it as more classes.
I've got problem with operations(in other classes) on already existing variables.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Goal: create an array from an 'if statement' that I can use for my object.
Here is the code. I want to use the method laneChoice() to determine which array to create, I plan on using more 'else if' statements. but for the time being, I keep getting a NullPointerException Which i assume that the reason being that private String[] Matchup is not updating?
private String[] Matchup;
.
public class ChampionAnalysis {
private String lane;
private int aggression;
private String tankOrDps;
private String damageType;
private int mechanics;
private String champion=null;
private String[] Matchup;
public ChampionAnalysis(String lane, int aggression, String tankOrDps, String damageType, int mechanics) {
this.lane = lane;
this.aggression = aggression;
this.tankOrDps = tankOrDps;
this.damageType = damageType;
this.mechanics = mechanics;
}
public String[] laneChoice(){
if(lane.equals("TOP")){
String[] Matchup = new String[] {"Aatrox", "Camille","Cho'Gath","Darius","Dr.Mundo","Galio","Garen","Gnar"
,"Hecarim","Illaoi","Jarvan IV","Kled","Malphite", "Maokai","Nasus","Nautilus","Olaf"
,"Poppy","Renekton","Shen","Shyvana","Singed","Sion","Trundle","Udyr","Vladimir","Volibear"
,"Wukong","Yorick","Zac"};
}
return Matchup;
}
public String toString(){
return (Matchup[1]);
}
Change the laneChoice method to
public String[] laneChoice(){
if(lane.equals("TOP")){
Matchup = new String[] {"Aatrox", "Camille","Cho'Gath","Darius","Dr.Mundo","Galio","Garen","Gnar"
,"Hecarim","Illaoi","Jarvan IV","Kled","Malphite", "Maokai","Nasus","Nautilus","Olaf"
,"Poppy","Renekton","Shen","Shyvana","Singed","Sion","Trundle","Udyr","Vladimir","Volibear"
,"Wukong","Yorick","Zac"};
}
return Matchup;
}
What you are currently doing is creating an array in the if statement. However, that array goes out of scope outside the if statement. When you say return Matchup;, Matchup refers to the array declared in the class, which has not been initialized. Therefore, NullPointerException occurs.
This question already has answers here:
Printing all variables value from a class
(9 answers)
Closed 6 years ago.
I have this simple class:
public class Events{
Boolean wentToGym;
String eventsToday;
public Events(Boolean wentToGym, String eventsToday){
this.wentToGym = wentToGym;
this.eventsToday = eventsToday;
}
Now for some reason I need to iterate through these fields and print them. As they are from different types, I thought I would use the Object declaration in the for-loop:
public static void main(String[] args){
Events events = new Events(true, "first trial");
for(Object e: events.getClass().getDeclaredFields){
System.out.println(e.toString);
}
}
Unfortunately not working because the object has no toString method. It gives me the same result you get when you try printing an array. And I dont know how to cast them inside the loop as they are declared as objects. Whats the best way to iterate through the attributes of a class and print them?
Edit: the question some guys rushed into referring to as duplicated is about attributes all of the same type (Strings), so there is no need for using an object nor the problem is the same. Its always a good idea to try helping by even reading the whole thing even if its harder than feeling important by simply flagging a question.
Is this what you're looking for?
import java.util.Arrays;
public class Events {
Boolean wentToGym;
String eventsToday;
public Events(Boolean wentToGym, String eventsToday) {
this.wentToGym = wentToGym;
this.eventsToday = eventsToday;
}
public static void main(String[] args) {
Events events = new Events(true, "first trial");
Arrays.stream(events.getClass().getDeclaredFields()).forEach(field -> {
try {
System.out.println(field.getName() + ": " + field.get(events));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
}
}
Output:
wentToGym: true
eventsToday: first trial
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am a bit lost...I'm learning Java and have to program a small poll command line application.
We are supposed to program it in german first(to be consistent between us all), so I'll try to translate it, so it's easier to read for you.
My problem is, that it's throwing an exception (while compiling) as following:
Exception in thread "main" java.lang.NullPointerException
at communication.Poll.addQuestionItem(Poll.java:18)
at main.PollTool.main(PollTool.java:8)
am I initializing my array "questionItems" wrong? Aren't I supposed to do it like that? What's wrong here? Did I forget something? :(
main.PollTool:
package main;
import communication.Poll;
public class PollTool {
public static void main(String[] args) {
Poll poll = new Poll ("Best Smartphone:",3);
poll.addQuestionItem("iPhone"); //<--line 8
poll.addQuestionItem("Android");
poll.addQuestionItem("Windows Phone");
poll.askQuestions("This poll determines the polularity of different Smartphones.");
}
}
communication.Poll:
package communication;
import java.util.Scanner;
import calculations.QuestionItem;
public class Poll {
private String questionTitle;
private QuestionItem[] questionItems;
private int count;
private Scanner in = new Scanner(System.in);
public Poll(String s,int arraySize){
questionTitle = s;
questionItems = new QuestionItem[arraySize]; //<--problem here?
}
public void addQuestionItem(String s){
if(count<questionItems.length){
questionItems[count++].setItemText(s); // <--exception here
}
}
public void askQuestions(String topic){
System.out.println(topic);
System.out.println(questionTitle);
for(int i=0; i<questionItems.length; i++){
System.out.println("- - - "+ questionItems[i].getItemText() +" - - -");
System.out.print("Your numerical answer: ");
questionItems[i].vote(in.nextInt());
}
}
void evaluation(){
//not ready :)
}
}
calculation.QuestionItem:
package calculation;
public class QuestionItem {
int count;
int overall;
String text;
public void vote (int pointValue){
overall += pointValue;
count++;
}
public double getDurchschnitt(){
return (double) overall/count;
}
public void setItemText(String s){
text = s;
}
public String getItemText(){
return text;
}
}
When you initialize an array of objects like this:
questionItems = new QuestionItem[arraySize];
All of the values are null by default.
In addQuestionItem, you try to call a method on an object in the array. However, that object starts off null, so this line of code doesn't work:
questionItems[count++].setItemText(s);
What you have to do is initialize the object before setting the text:
questionItems[count] = new QuestionItem();
questionItems[count].setItemText(s);
count++;
Alternatively, you can do what Constant suggested, and initialize all the objects when you initialize the array.
By the looks of it, you're making the array but it doesn't contain the objects yet. You probably want this in the constructor instead.
questionItems = new QuestionItem[arraySize];
for(int i = 0; i < questionItems.length; i++) {
questionItems[i] = new QuestionItem();
}