Replace in a Arraylist with more Columns - java

So for an assignment i need to to replace an Element in an ArrayList. As an example i have a Team Class
class Team {
int id, int points;
String name;
}
I need to find the ID of the Team in the List and replace the Points with new Points. I know i can get the index of the ID with list.get(i).id but i don't know how to replace the Points there. I know that there is a list.set() command but i didn't find how to replace the Points of the Team in the ArrayList because the set Command doesn't accept "i" as a Parameter.
Already thanks in advance

I suppose you have an ArrayList of Team objects and you want to change the points of a team with a specific id?
In order to do this, you can do:
for(int i = 0; i < yourlist.size(); i++)
if (yourlist.get(i).id == yourID)
yourlist.get(i).points += 1;
break;

Each element of the list will be a Team. As you said, first you need to get the element Team that has the ID of the Team you want to change the points of. To do this, you need to somehow iterate over the list and find that such element(s). Watch out, as List<T>.Get(int i) will give the element present at index i of the list, not the Team with ID i. Then, to set the points of the Team, either assign a value directly, or, better yet, define and use setter methods. List<T>.Set(int i, T elem) replaces the Team at index i, for the Team elem, so it shouldn't be what you want to be doing, as points, the thing you want to change, can be changed directly on the instance already present in the list. To use Set, you'd have to create a new Team instance with a new value for points.

Related

Track first index at which a duplicate value is observed when using local variable

Given int[] arr = [7, 2, 5, 2]; and int index;, how can I use a for loop to make sure that index is assigned to 1 (the first index at which 2 was observed in arr) and not 3 (the last index at which 2 was observed in arr)?
I'm thinking using a break; statement but I'm not sure how to implement the syntax.
You can add every array value to a hashmap with the value as key and the index as value, that way if a key already exists you know at which index it was.
Alternatively you could also have the hashmap value be a list so you can store for each value, all of the indexes in which is appears in the array.
If you're using embedded for loops (the suggested answer when you search this question) one of your loop counters will point to the first instance while the second will point to the second instance. Just use the correct variable.
You can break a for loop once you've found what you want, like this:
for (int i = 0; i < arr.length; i++) {
if (foundDuplicate()) {
break;
}
}
// You end up here after the break
This gets you out of the for loop
You can also find the duplicate whichever way you want and then iterate over the array until you find the first instance.
Depends on what arbitrary rules have been placed on this exercise

searching through array-lists , having a hard time

I have a method here, its job is to take in 3 array lists, and return a value.
THE 3 ARRRAY LIST specific jobs
names entereed by user
this is a arraylist with all names I made, these are player names
for each name , i have given a specific value. I am using this to cross reference my position with that value I assigned that name
I know the third might be confusing to understand, so ill try breaking it down a bit. so say someone enters a name, i look up that name in my playernames, and once i find that position, I can the position to access that players ranking from playerNumber. Because I put the names in one list, and numbers in another. The positions match for names and numbers in both lists
My problem is that I keep getting 0, as my returned result. Im not sure why, please advise :<
**unrealated: **Guys the reason why im using arraylists is because this is as far as I have learned in java. I will be learning new topics as time comes, im just trying my best to use the skills I have to make a fun project. So sorry if its really nooby, this is the best I can do right now
public static int meth(List names, List searchingLis, List nameNumber){
int totalGive=0;
int totalRecieve=0;
int sizer=names.size()-1;
int ret=-1000;
int makeSureAllPlayerAdded=sizer;
int returningValue=0;
do{
for(int i=0;i<names.size();i++){
int currenSearchRanking=(int) nameNumber.get(i);
if(names.get(i).equals(searchingLis.get(i))){
int valueToLookUpInNames=i;
int AddingValue=(int) nameNumber.get(valueToLookUpInNames);
returningValue=returningValue+AddingValue;
System.out.println(returningValue+"ret vales");
makeSureAllPlayerAdded--;
}
}
return returningValue;
}while(makeSureAllPlayerAdded<=0);
}
I understand you're saying that searchingLis and nameNumber have matching positions which effectively represent a row, and that names is just an arbitrary list of unmatched names provided by the user.
Your most fatal flaw, then, is in the line if(names.get(i).equals(searchingLis.get(i))){.
In it, you'll only see a match from names in your searchingLis if it is in the same position. So, if searchingList held ["John","Mary"] and names held ["Mary"], then there would be no match because you only look at the searchingList member in position 0, rather than comparing each member of searchingList to each name.

Item List for Text RPG

I'm trying to make a simple text-based RPG to keep my skills sharp between semesters. I'm trying to create the different elements separately before bringing them together. Right now, I'm trying to create a basic generic list to hold "Item" objects for the player (things like potions and bombs etc.).
As you can see in the image, I'm trying to tie the index values to the individual items in the list. Since I added the same item to the list three times, it shows up three times (which is what I want), but I'm wondering how I can have this and somehow have the index value represent that actual number of items instead of just the true index value of the objects added.
Essentially, I want to be able to have the player select a number and then use the item that way. I'm sure I'm missing something obvious, I appreciate any insight!
Use a for loop instead of a for-each loop so you have access to a counter.
for (int i = 0; i < playerItems.size(); i++)
{
System.out.println(i + ". " + playerItems.get(i).getName());
}
Or, just use the ctr variable you already have and increment for each item.
for (Item i : playerItems)
{
ctr+=1;
System.out.println(ctr + ". " + playerItems.get(i).getName());
}
Also, you don't need to check if playerItems contains i. You will never get an item in a for-each loop that isn't in the collection.

What is the most efficient way (speed-wise) of maintaining a sorted ArrayList in Java?

Which of the following two methods would be the faster one of keeping an ArrayList sorted ?
Inserting the element in its place
Calling push, then call Collections.sort(myList)
There is different kinds of collections. You could choose one that keeps your data sorted.
It would probably be more efficient to insert in the right position, for example by using Collections.binarySearch(list, elementToInsert):
int index = Collections.binarySearch(list, element);
if (index < 0) index = - (index + 1);
list.add(index, element);
If you don't need random access and your entries are unique (which seems to be the case based on your comment), you could also use a TreeSet:
NaivigableSet<User> users = new TreeSet<> (Comparator.comparing(User::getId));
The set will always be sorted based on the user ids which must be unique.
If your requirement asks for a continuous sorting after every insert, i think you should try alternate approach than the current one as this in itself is not time efficient. For a elaborate explanation for possible solution you must look at Sorted array list in Java

How can I add up values of an array object?

I have an array that created 5 objects. Each object has two strings and a int. Lets call the int "number". How can i add up the "number's" of each object into a final number, assume that the numbers change so i cannot simply just put 5 + 3 etc.. For example
Question question[] = new Question[5];
public Constructor()
{
String1 = "null";
Sting2 = "null";
number = 0;
}
SO i have five objects that look like this, they all have a different value. Number refers to a score, So if the user does something right, the number will be added to a variable, i need to know how to add up the 5 variables when i execute the 5 objects in something like.
for (i=0; i < Question.length; i++)
{
object.dostuff
}
Many things have to happen first:
Initialize the array: seems you got that one covered.
Initialize objects within the array: Make sure every cell of your array actually contains a question instance (or to be more precise: a reference to a Question instance).
Iterate over the array: here your loop seems to go over the class (Question, with capital Q) but you need to iterate over the array (question with a small q). Piece of advice, since the variable question here represents an array of question it would make more sense if you make your name plural (questions) to help illustrate that this is an array. Basic rule is to make the name as explicit as possible, so questionArray would be an even better name. Past a certain point it's a question of taste. Rule of thumb is that if you have to look at the declaration of the variable then it's probably not named correctly.
access methods, properties etc of the objects: when iterating over the array you need to access the right index (questions[i]) then access the members of this object (questions[i].doStuff). If you aim for OOP (which I assume is the point here) then you may want to make the obvious operations as functions of your Question class. Then simply call this function with the proper parameter (questions[i].setNumber(i)). It all depends on what you need it to do.
Hope this helps (if this is a homework related question you should tag it as such, that would maximize your chance to get help here).
Don't use Question.length, use question.length
Add an accessor method and a method to increment the scores.
use map to extract the numbers from the list of tuples then use reduce to accumulatively sum the numbers.
list=[("1 this is sentence 1","1 this is sentence 2",1),("2 this is sentence 1","2
this is sentence 2",2),("3 this is sentence 1","3 this is sentence 2",3)]
numbers=map(lambda x: x[2],list)
result=reduce(lambda x,y: x+y,numbers)
print(result)
output:
6

Categories

Resources