searching through array-lists , having a hard time - java

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.

Related

Sum of Arrays In Given Range, Count of certain #'s in an Array etc

I am having trouble getting through my Java labs. I don't have the best instructor and they are due tomorrow. If someone could help me and give a brief summarization of the code, they would use. I have posted this lab description below and attached the code of the runner file in the comments.
Lab Description: Write several array manipulation methods. One method will sum up a section of a provided array, another method will count up how many of a certain number occur in the array, and the last method will remove all of a certain value from the array.
I have tried a forloop to iterate through the array and select the elements but I am stumped on how to select the range and add them.

Replace in a Arraylist with more Columns

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.

Can a 2D array hold an array within a given point?

I am a fairly newbie programmer with a question on arrays in Java. Consider a 2D array, [i][j]. The value of i is determined at run time. The value of j is known to be 7. At [i][6] and [i][7] I want to be able to store a deeper array or list of values. Is it possible to have something like an array within an array, where there is an x and y axis and a z axis at the point of [i][6] and i[7] or will I need a full 3D cube of memory to be able to store and navigate my data?
The Details: My goal is to run a query which takes certain information from two tables (target and attacker) My query is fine and I can get a resultset. What I really want to be able to do is to store the data from my resultset and present it in a table in a more useful format while also using it in a data visualization program. The fields I get are: server_id, target_ip, threat_level, client_id, attacker_ip and num_of_attacks. I could get 20 records that have the same server_id, target_ip, threat_level, client_id but different attacker_ip and num_of_attacks because that machine got attacked 20 times. A third dimension would allow me to do this but the 3rd axis/array would be empty for server_id, target_ip, threat_level, client_id
UPDATE after reviewing the answers and doing some more thinking I'm wondering if using an arraylist of objects would be best for me, and/or possible. Keeping data organized and easily accessible is a big concern for me. In psedu code it would be something like this:
Object[] servers
String server_id
String target
String threat_level
String client_id
String arr[][] // this array will hold attacker_ip in one axis and num_of_attacks in the other in order to keep the relation between the attacking ip and the number of attacks they make against one specific server
In first place, if you have an array DataType[i][j] and j is known to be 7, the 2 greatest indexes you can use are 5 and 6, not 6 and 7. This is because Java array indexes are 0-based. When creating the array you indicate the number of elements, not the maximum index (which always is one less than number of elements).
In second place, there is nothing wrong with using multidimensional arrays when the problem domain already uses them. I can think of scientific applications, data analysis applications, but not many more. If, on the contrary, you are modelling a business problem whose domain does not use multidimensional arrays, you are probably better off using more abstract data structures instead of forcing arrays into the design just because they seem very efficient, experience in other languages where arrays are more important, or other reasons.
Without having much information, I'd say your "first dimension" could be better represented by a List type (say ArrayList). Why? Because you say its size is determined at runtime (and I assume this comes indirectly, not as a magic number that you obtain from somewhere). Lists are similar to arrays but have the particularity that they "know" how to grow. Your program can easily append new elements as it reads them from a source or otherwise discovers/creates them. It can also easily insert them at the beginning or in the middle, but this is rare.
So, your first dimension would be: ArrayList<something>, where something is the type of your second dimension.
Regarding this second dimension, you say that it has a size of 7, but that the first 5 items accept single values while the last 2 multiple ones. This is already telling me that the 7 items are not homogeneous, and thus an array is ill-indicated. This dimension would be much better represented by a class. To understand this class's structure, let's say that the 5 single-valued elements are homogenous (of type, say, BigDecimal). One of the most natural representations for this is array, as the size is known. The 2 remaining, multi-valued elements also seem to constitute an array. However, given that each of its 2 elements contains an unidentified number of data items, the element type of this array should not be BigDecimal as in the previous case, but ArrayList. The type of the elements of these ArrayLists is whatever the type of the multiple values is (say BigDecimal too).
The final result is:
class SecondD {
BigDecimal[] singleValued= new BigDecimal[5] ;
ArrayList<BigDecimal>[] multiValued= new ArrayList<BigDecimal>[2] ;
{
multiValued[0]= new ArrayList<BigDecimal>() ;
multiValued[1]= new ArrayList<BigDecimal>() ;
}
}
ArrayList<SecondD> data= new ArrayList<SecondD>() ;
In this code snippet I'm not only declaring the structures, but also creating them so they are ready to use. Pure declaration would be:
class SecondD {
BigDecimal[] singleValued;
ArrayList<BigDecimal>[] multiValued;
}
ArrayList<SecondD> data= new ArrayList<SecondD>() ;
Array size is not important in Java from a type (and thus structural) point of view. That's why you don't see any 5 or 2.
Access to the data structure would be like
data.get(130).singleValued[2]
data.get(130).multiValued[1].get(27)
A possible variant that could be much clearer in certain cases is
class SecondD {
BigDecimal monday;
BigDecimal tuesday;
BigDecimal wednesday;
BigDecimal thursday;
BigDecimal friday;
ArrayList<BigDecimal> saturday= new ArrayList<BigDecimal>() ;
ArrayList<BigDecimal> sunday= new ArrayList<BigDecimal>() ;
}
ArrayList<SecondD> data= new ArrayList<SecondD>() ;
In this case we are "expanding" each array into individual items, each with a name. Typical access operations would be:
data.get(130).wednesday
data.get(130).sunday.get(27)
Which variant to choose? Well, that depends on how similar or different the operations with the different itemes are. If every time you will perform and operation with monday you will also perform it with tuesday, wednesday, thursday, and friday (not saturday and sunday because these are a completely different kind of thing, remember?), then an array could be better. For example, to sum the items when stores as an array it's only necessary:
element= data.get(130) ;
int sum= 0 ;
for(int e: element.singleValued ) sum+= e ;
While if expanded:
element= data.get(130) ;
int sum= 0 ;
sum+= element.monday ;
sum+= element.tuesday ;
sum+= element.wednesday ;
sum+= element.thursday ;
sum+= element.friday ;
In this case, with only 5 elements, the difference is not much. The first way makes things slightly shorter, while the second makes them clearer. Personally, I vote for clarity. Now, if instead of 5 items they would have been 1,000 or even as few as 20, the repetition in the second case would have too much and the first case preferred. I have another general rule for this too: if I can name every element separately, then it's probably better to do exactly so. If while trying to name the elements I find myself using numbers or sequential letters of the alphabet (either naturally, as in the days of the month, or because things just don't seem to have different names), then it's arrays. You could still find cases that are not clear even after applying these two criteria. In this case toss a coin, start developing the program, and think a bit how things would be the other way. You can change your mind any time.
If your application is indeed a scientific one, please forgive me for such a long (and useless) explanation. My answer could help others looking for something similar, though.
Use ArrayList instead of array primitives. You can have your three dimensions, without the associated inefficient wastage of allocating a "cube"
If not creating a custom class like #nIcE cOw suggested Collections are more cumbersome for this kind of thing than primitive arrays. This is because Java likes to be verbose and doesn't do certain things for you like operator overloading (like C++ does) or give you the ability to easily instantiate ArrayList from arrays.
To exemplify, heres #sbat's example with ArrayLists;
public static <T> ArrayList<T> toAL(T ... input) {
ArrayList<T> output = new ArrayList<T>();
for (T item : input) {
output.add(item);
}
return output;
}
public static void main(String[] args) {
ArrayList<ArrayList<ArrayList<Integer>>> a = toAL(
toAL(
toAL(0, 1, 2)
),
toAL(
toAL(4, 5)
),
toAL(
toAL(6)
)
);
System.out.println(a.get(0).get(0).get(2));
System.out.println(a.get(1).get(0).get(1));
System.out.println(a.get(2).get(0).get(0));
}
Of course, there's nothing syntactically wrong with doing:
int[][][] a = {{{0, 1, 2}}, {{4, 5}}, {{6}}};
System.out.println(a[0][0].length); // 3
System.out.println(a[1][0].length); // 2
System.out.println(a[2][0].length); // 1
In fact, that's what multidimensional arrays in Java are, they're arrays within arrays.
The only problem I see with this is that it might become confusing or difficult to maintain later on, but so would using ArrayLists within ArrayLists:
List<List<List<Integer>>> list = ...;
System.out.println(list.get(0).get(1).get(50)); // using ArrayList
However, there are still reasons as to why you might prefer an array over a collection. But ArrayLists or other collections may be preferable depending on the circumstance.

Returning the most common guide name in a trip array

I am new to java, and a new student of Computer Science.
I have a question: How can I find the most common name in an array that contains objects
with information about trips?
The array has objects that each of them contains information about trips, and there is the name of guide.
By logic, I understand that I need first to get all guide names, then count each name,
then compare the counters of each name, find the maximum counter, and return the guide that
contains that maximum counter.. but how do I do this?
Any suggestions?
There are a lot of ways to do it. You are on the right track in your approach. Here's a little more detail about how you could do the things that you mention, in java.
"get all guide names"
This means you have to write a loop over your array, and collect the names in some kind of data structure. Which data structure to use depends on what you want to do (more on this below).
"count each name"
Aha, so your data structure that collects the names should be able to also store the count for each name. One of the most versatile data structures in java is the Map. In this case, you could have a Map to store the count of each name.
"compare the counters", "find the maximum"
You can either do this after you've collected the names into a Map, but it's probably simpler to just do it as you go through the loop. As you loop over the items in the array, and get the name to update the count, you can also keep track of the "maximum count so far" and the name that goes with it. Any time you get a name whose new count is greater than this maximum, you would then have a new maximum and corresponding name (at least until you find a bigger one). Then at the end of the loop you will have the name that you are looking for.

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