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);
Related
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.
Say I have a .txt file that has information being split by a comma as such:
IN,Indiana,6634007
While this is a snippet which accesses that file and splits it:
for(int i=0; i < count; i++) {
line = bufferedReader2.readLine();
String space[] = line.split(",");
String abb = space[0];
String nme = space[1];
int pop = Integer.parseInt(space[2]);
states[i] = new State(abb, nme, pop);
}
The purpose of that was so that all the information in the txt file could be accessed, so for example this code would print exactly whats present on the .txt file:
System.out.println(states[0]);
would print:
IN,Indiana,6634007
My question is, how would I have it so that I can access the specific part of the array as in how would I print lets say just the name "Indiana" or the population "6634007"?
P.S I'm sorry if the title of my question did not make sense, I did not exactly know how to word it.
Somewhere, you have a class called State. states is an Array of this class. So you can add a getter to State:
public int getPop() {
return pop;
}
And call it on your Object like this:
System.out.println(states[0].getPop());
as states[0] is simply a State object.
Add more getters to access different fields.
if you just want to print every single line, you can try this like below:
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = null;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null ) {
list.add(line);
}
System.out.println(list.get(0));
// TODO realease resources
}
From your question what i can realise is, you are using State class to store the information. In such case, check the state class where the first parameter value is stored. Later to print the corresponding information, access its object variable as SapuSeven mentioned.
For eg.
public class State{
public String a;
public String b;
public int c;
public State(String x, String y, int z){
a=x;
b=y;
c=z;
}
}
now u can access like
System.out.println(states[0].b);
for printing the name of city
OR
you can simply print the value using index like this
System.out.println(states[0].split(",")[2]);
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.
I am working on a quiz app that takes a group of questions from my DB and displays each question once after a button click, preferably without duplicating the same question. I have a method called on initialization which gets an array of two arrays from my db, then splits it into two the separate arrays. One of those arrays I then want to use in another method. This is the first method (at the moment I am creating an array string from the list and storing that as a global variable for future use - I am also using a random value from that list to display in a textview):
private class showNextRandomQuestion extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
SQLDatabaseHelper db = new SQLDatabaseHelper(MainActivity.this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion2();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
List<String> answerSetIds = listList.get(1);
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
//get answer description for randomly selected question
String questionString = questionStrings.get(rand);
String answerSetId = answerSetIds.get(rand);
questionstringarray = questionStrings.toString();
//remove and square brackets from array of strings
String regex = "\\[|\\]";
answerId = answerSetId.replaceAll(regex, "");
mQuestionString = questionString.replaceAll(regex, "");
return mQuestionString;
}
#Override
protected void onPostExecute(String result) {
//take returned question from above and display it
questionView.setText(mQuestionString);
}
}
I am for some reason really struggling to figure out how I can use the list as it is rather than converting it into a string array ('questionstringarray'). You'll see from my next method, which is triggered by button click, that I had tried to take that string array and turn it back into a list, so I could use it again.
private class showNextRandomQuestion2 extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
List<String> array1 = new ArrayList<String>();
//remove and square brackets from array of strings
String regex = "\\[|\\]";
questionstringarray = questionstringarray.replaceAll(regex, "");
StringTokenizer questionDescr = new StringTokenizer(questionstringarray, ",");
first = questionDescr.nextToken();
first = first.trim();
second = questionDescr.nextToken();
second = second.trim();
third = questionDescr.nextToken();
third = third.trim();
fourth = questionDescr.nextToken();
fourth = fourth.trim();
fifth = questionDescr.nextToken();
fifth = fifth.trim();
array1.add(first);
array1.add(second);
array1.add(third);
array1.add(fourth);
array1.add(fifth);
Collections.shuffle(array1);
//remove and square brackets from array of strings
String regex1 = "\\[|\\]";
//remove values from string when shuffling through so not repeated
String bQuestionText = array1.remove(0);
bQuestionString = bQuestionText.replaceAll(regex1, "");
return bQuestionString;
}
#Override
protected void onPostExecute(String result) {
//take returned question from above and display it
questionView.setText(bQuestionString);
}
}
I don't obviously want to convert from a list in one method only to convert it back to a list in the next. Ultimately I want the first method to get the data from my db which I am happy with - display one of the strings within that method, then store that same list for use in another method where I will display the next string in the list (hopefully then remove it from the list) and on button click display then next string, and next.... - hence the 'Collections.shuffle'.
Any help appreciated. Thanks
And here is my new class which retrieves and stores the list for further use:
package com.example.quizapp;
import java.util.List;
import android.app.Application;
public class QuizQuestionBank extends Application {
#SuppressWarnings("unused")
private List<String> questionStrings;
public List<String> getQuestionStrings(List<String> questionStrings2) {
SQLDatabaseHelper db = new SQLDatabaseHelper(QuizQuestionBank.this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion2();
// questionStrings.clear();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
// List<String> answerSetIds = listList.get(1);
return questionStrings;
}
public List<String> setQuestionStrings(List<String> questionStrings) {
return this.questionStrings = questionStrings;
}
}
Ideally you have three concerns here;
1. Return required data from the database, ensure it is in an appropriate format for all client methods.
2. Store the returned data
3. Select (random) question from the returned data.
I would return the data from the database in one method, the return from which I would then store in an instance variable of a class, perhaps called QuizQuestionBank or some such. This would have a method from which a question will be returned.
This way the method return the question can choose a random question from the list or simple the top one, or remove the used questions from listed. Depending on your requirement and it is transparent to the client class, all the client class knows if it calls method on QuizQuestionBank and a question is returned, it doenst worry about how that may be stored or selected.
Simplest way is to use a class for your Question object.
and after getting list of questions from db in a list variable, store that variable data with Application Class using setter methods and whenever required get it by calling getter method(of Application class) inside activity.
and use any shuffling method before starting quiz session(new attempt of quiz).
Edited:
Use it like below:
package com.example.quizapp;
import java.util.List;
import android.app.Application;
public class QuizQuestionBank extends Application {
#SuppressWarnings("unused")
private List<String> questionStrings;
public List<String> getQuestionStrings() {
return questionStrings;
}
public List<String> setQuestionStrings(List<String> questionStrings) {
return this.questionStrings = questionStrings;
}
}
Now use the code to get data from Database only once, before starting quiz,
and put that data into QuizQuestionBank class's questionStrings variable using setter method.
Set it from activity like below:
((QuizQuestionBank) getApplication()).setQuestionStrings(List<String> questionStrings);
And get it within an activity like below:
List<String> questionStrings = ((QuizQuestionBank) getApplication()).getQuestionStrings();
or get it within a fragment:
List<String> questionStrings = ((QuizQuestionBank) getActivity().getApplication()).getQuestionStrings();
of if any other class:
List<String> questionStrings = ((QuizQuestionBank) context.getApplicationContext()).getQuestionStrings();
where context(Context type) will be initialized with passed context argument.
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();
}