Adding up values of items in an ArrayList [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
ive hit a road block and im stuck with a question on my work.
Here is the question:
Provide an implementation of the getLoad method that adds up the individual weights of
the items in the items list and returns the total.
The items list is:
ArrayList<Item> items;
Ive done what i thought was right but for some reason its not working.
Any help on what is wrong, or if what im doing is wrong? thanks
#Override
public int getLoad() {
int load = 0; //declare the variable
for (Item i : items) { // for each item in the list of items
load = load + i.getWeight() ; // load equals the weight of the item and adds on
}
return load; //returns it
}

The one thing I could see going wrong is if getWeight() returns a double. In that case, you should make int load: double load instead

With the limited information you've provided here, I can only take a wild guess that the problem is either:
The list items is empty even though it shouldn't be. Make sure that Items actually get added to the list! Use a debugger or a printed message to find out if the item list is empty on getLoad().
Weights for each Item are not assigned correctly, so getWeight() returns zero for each of them. Make sure that each Item added to the list actually gets assigned its proper weight.
Posting more code would help us give a better answer.

Related

Randomized questions and answers

I'm making a quiz game with 3 different choices. First, I created a list with a total of 17 questions and answers. Then to make sure that the order is ramdomized every time I play the game I will Collections.shuffle(MyList) the whole list at the beginning.
My structure:
I'm picking a question at a randomized position in the list. But, the question is randomized between 0-2, so if I get "1", I will get the question like this Mylist.get(1).getQuestion().
The choices/answers are at the position 0-2 in the list. (The first choice will be: Mylist.get(0).getAnswer(), the second Mylist.get(1).getAnswer() and the third Mylist.get(2).getAnswer()) By doing this, one of the answers will be correct since the index of the question is also between 0-2. And to keep the right choice in a randomized position.
However, the problem is, every time I answer a question, this question will be removed from the list. (Mylist.remove(1)) So, in the end, there will be less than 3 items left and I won't have 3 unique answers. My goal is to have 3 different choices with randomized order on every question, and one of them is, of course, correct. I'm new into programming and don't really know how to fix it. (Everything is in Netbeans).
Thanks in advance!
So you have 17 questions and each question has a correct answer, and you need to show each of these questions with three proposed answers, one of which is correct and other two are wrong (but these are correct answers to other questions)?
Shuffle the list only once, at the beginning of the program. Then, use a for loop to present the questions in order. Don't remove answered questions; the loop will ensure that each question is asked only once. Since the list is shuffled, the user will not be able to predict questions.
Then, fill in the proposed answers: put the correct answer at a random position, and fill the remaining positions with random other answers (use the while loop to ensure that these answers are different from the correct one and from each other).
Something like:
Collections.shuffle(MyList);
for(int i=0; i<MyList.size(); i++){
System.out.println(MyList.get(i).getQuestion();
Answer[] answers=new Answer[3];
int correct=(int)(Math.random()*3);
answers[correct]=MyList.get(i).getAnswer();
int j=i, k=i;
while( j==i ){
j = (int)(Math.random()*MyList.size());
}
answers[(correct+1)%3] = MyList.get(j).getAnswer();
while( k==i || k==j ){
k=(int)(Math.random()*MyList.size());
}
answers[(correct+2)%3] = MyList.get(k).getAnswer();
System.out.println("Answers:");
for(int t=0;t<3;t++){
System.out.println(answers[t]);
}
}

two arrays are always equal [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this code
for (int i=0; i<tini.length; i++){
tini[i].tempLabel.setText("Temp: "+ Float.toString(tempArray[i]) +"°" );
out_status[i] = tini[i].alarm;
frame.statusLabel.setText("Connetction: OK, String: OK");
}
System.out.println("old: " + Arrays.toString(out_status_old));
System.out.println("new: " + Arrays.toString(out_status));
if (Arrays.equals(out_status, out_status_old) ){
System.out.println("UGUALI");
}
out_status_old = out_status;
the resulting arrays are always equal. I cannot understand the reason.
Using a Button in JFrame, in a GUI interface i can modify the value of alarm, but both the old value and the actual one change at the same time!
When you access and then update the elements of one array, you're also updating the elements of the other array because they are referencing the same objects. You need to create separate items within each array while populating the arrays.
You left out an important part of your program which is where you're actually populating these arrays. Odds are, you are not doing a deep copy.
Deep copy of an object array
The line out_status_old = out_status; does not create a copy of the array. You have just two variables, out_status and out_status_old, pointing to the same array.
If you want to create a proper copy of the array, you can e.g. use Arrays.copyOf (or one of its variants).

How to prevent NullPointerException in my code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here's a brief explanation of my program:
User keys in data
Data is stored in vector
User may choose to key in data again...
Before the program is closed, a summary screen of data will be displayed.
The problem I'm facing now is that the for loop is executed even before data is stored in it, while what I want is for the for loop to run only summary screen is displayed.
Is there a way to tackle this problem?
SummaryPanel.class (Partial code)
list = new JList<String>();
scroll = new JScrollPane(list);
model = new DefaultListModel<String>();
for(int i=0; i<con.retrievePersonalVector().size(); i++){
model.addElement(((PersonalRecord)con.retrievePersonalVector().get(i)).getLoginName()); //NPE
list.setModel(model);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int selected = list.getSelectedIndex();
}
});
A couple of things:
Vector<?> persRecs = con.retrievePersonalVector();
for (int i = 0; i < persRecs.size(); i++) {
PersonalRecord persRec = (PersonalRecord)persRecs.get(i);
if (persRec != null) (
model.addElement(persRec.getLoginName());
}
}
In the original code the retrievePersonalVector was done at every loop step twice: checking the size and getting an element. Instead of 2N times, retrieval is now done once.
Then the model was passed to the component in the loop. Mabye a genuine decision, to see a something, but that probably does not work here, hence I close the loop early. Also adding a listener should be done once. (Or you maybe lost a } on copying together the question.
First of all, you should not use Vector anymore. Prefer List<T> list = Collections.synchronizedList(new ArrayList<T>()). Secondly, if the NullPointerException is indeed thrown where you spot it, it is probably because the Vector contains some null elements, so you should insure that you do not store any null element. Last, why not checking if the summary panel is displayed before looping (either with an isVisible() or a local boolean) ?

Remove elements from arraylist based on a condition [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an ArrayList whose each element is of type DataType, where DataType is a class:
class DataType{
String dId;
String dType;
String rId;
}
I need to remove all such elements from the list whose rId is equal to any other element's dID.
i.e. if DataType D1 has value of dID as "abc" and DataType D2 has value of rID as "abc", than remove both D1 and D2 from the list.
Could someone please suggest the most appropriate approach for doing this.
The easiest would be to traverse the list once and create a HashMap<String, List<DataType>>.
You will map every object to their dID which forms the primary key.
After that you can iterate over your ArrayList, check the rId of the current object and see if it's in the HashMap. HashMap has O(1) lookup time so this should be a non issue. If the value is present, remove the current value (you're using an Iterator to prevent a ConcurrentModificationException) and remove the objects inside the value-part of the key-value pair as well.
Make sure you have correctly implemented .equals(Object o) and .hashcode().

How to check an array before populating it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Does anyone know how can I populate an array that checks if the positions are filled before filling them, and if they are already filled and if that array position is filled it increments to the next one.
Thanks
Primitive array elements are never empty. For example in an int array all elements will be initialized to 0.
So if you want to check for filled or not, initialize the array elements to a value which it is not going to take. say -1. Then each time you make an entry check for -1. The dummy value initialization is necessary as you can not check for 0, because 0 can be a valid data as well
// Initialization part
int [] arr= new int [17];
for(int i=0;i<arr.length;i++)
{
arr[i]= -1;
}
Hope you will do the checking part yourself
I am assuming (possibly incorrectly) that you either a) want a method that inserts object into the first available (i.e. not null) spot in the array at or past the argument integer or b) want to insert repeatedly into the array using the method in a)
the method in a) would basically be as follows
public <Type> void myInsertMethod(Type[] array,Type item,int position)
{
while (array[pos]!=null)
{pos++;}
array[pos]=item;
}
if you want to do this repeatedly on the same array, just call the method repeatedly, with different positions and items.
You can check if the position you are going to fill it's not null, or empty, or at least the stored value it's different to the one you are going to put
if(array.get(index) != "" && array.get(index) != null) && array.get(index) != newObject){
array.add(newObject);
}
Then, depending on the stored value type, you can ddo some more checks, for example in the cas e of the int, as RookieB says, you can check if the object is different to 0
Hope it helps

Categories

Resources