How can I add up values of an array object? - java

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

Related

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.

Adding int to an array

First off don't call this a duplicate unless you actually find a thread that works for exactly what I'm trying to do, as I've gone through about 50 threads that aren't helping.
~Problem: I don't know how to correctly add an integer to an array like "private int test[] ={}"
~My code:
private int generatedList[] = {};
private int lastInt = 1;
private void startList() {
if (generatedList.length == 30000) {
System.out.println(generatedList);
} else {
generatedList[lastInt+1] = generatedList[lastInt];
lastInt++;
System.out.println(generatedList);
startList();
}
}
~What I'm trying to accomplish: if the length of the list is less than 30,000 add the last int to the array then lastInt++, so after looping say 5 times the list will print like this: 1,2,3,4,5
How do I add the "lastInt" to the generatedList[]?
Arrays in Java are of a fixed size. The one you declared is of size 0, in fact. You won't be able to append to the end of it. Check out the ArrayList class, it will help you.
private ArrayList<Integer> generatedList;
...
generatedList.add(1234);
However, there is a bigger problem with your code. Your recursive implementation is going to be extremely slow, and it doesn't have an initialization for the first value in the array. It would be much better to use a primitive array of fixed size 30,000, and simply loop from 0..30k and fill in the values by index. I leave that as an exercise for you since this is probably related to some homework assignment :)
Arrays are not extendible. This is by design.
I suggest using an ArrayList. It's like an array (can index any property, works almost as fast in terms of runtime complexity) but has the additional properties that you can add and remove items.
The easy way to do this is to change generatedList into ArrayList<Integer>. If you want to preserve an array, you can always create a new array and copy over the contents. (ArrayLists are easier, though.)
Your trying to add new elements to an array of size zero size. Use an arraylist or specify array size first.

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 arrays and looping

I am new to Java and am assigned to design a program that grabs input from a file and inserts it to certain parts of an array, then exports that data. I have the code to read the file into a string array.
Two questions:
1.) How can I create a loop to create a numbered list with blank data following it? (see my code snippet below) I am trying to create a list that looks like the following:
1 0000 0000 00000 ...
2 0000 0000 00000 ...
Do you see any issues with my loop below?
for (int x = 0; x < array.length; x++) {
array[x] = Integer.toString(y);
y++;
while (x < 16) {
x++;
array[x] = "00000";
}
}
2.) Can I use a single method to return two array values? I would like two arrays filled, then their values returned for use in other methods. I found a method I could use, but I'm not sure how to go about properly implementing it.
I have a code snippet below:
public static Object[] rtrStr() {
//...blah blah
return new Object[]{array1, array2};}
2) You can return an array (or List) of arrays, if you wish:
public static String[][] rtrStr() {
// ...blah blah
String[][] arr = new String[][2]; // syntax might not be exactly correct
arr[0] = array1;
arr[1] = array2;
}
Note: I'm unsure about the exact syntax on the noted line, but the idea is sound. Personally, I would prefer using a List instead.
With that said, you should consider the meaning of the data in each array. It might make sense to create a custom class which wraps the array and clarifies the semantics. This also makes it easier to return an array or List from any method since the elements will be objects of your new custom class.
Do you see any issues with my loop below?
Yes, multiple: Your code is what I would call bad code. Even if it does what you want (and I'm not sure of that), it's extremely difficult to understand for such a simple task.
You're using x and y as counter-variable names. Don't do that when more than one counter is involved! It's hard to understand exactly what counter is counting what.
Your inner loop is messing with the counter-variable of your outer loop. If that was by design, don't ever do this. It makes the code very difficult to understand.
Also, if the array should hold something like a table (rows and columns) like in your example output, you'll need a two-dimensional array.
Can I use a single method to return two array values?
Yes, why not? You're actually returning one array with two values. You can however not return two arrays from a single method.

Concatenating 2 2D arrays in java?

I've got 2 2D arrays, one int and one String, and I want them to appear one next to the other since they have the same number of rows. Is there a way to do this? I've thought about concatenating but that requires that they be the same type of array, so in that case, is there a way I could make my int array a String array?
If you want an array that can hold both Strings and ints, you basically have two choices:
Treat them both as Objects, so
effectively Object[][]
concatArray. Autoboxing will
convert your ints to Integers.
Treat them both as Strings (using
String.valueOf(int) and
Integer.parseInt(String)).
I don't know for a fact, but would guess autoboxing is a less expensive operation that converting ints to string and back.
Further, you can always find out the value type of a cell in the array by using instanceof operator; if values are converted to String, you actually need to parse a value to find out if its just a bit of text or a text representation of a number.
These two considerations -- one a guess, the other possibly irrelevant in your case -- would support using option 1 above.
Just cast the ints to Strings as you concatenate. The end result would be a 2D array of type String.
To concatenate an int to a String, you can just use
int myInt = 5;
String newString = myInt + "";
It's dirty, but it's commonly practiced, thus recognizable, and it works.
There are two ways to do this that I can see:
You can create a custom data object that holds the strings and ints. This would be the best way if the two items belong together. It also makes comparing rows easier.
You can create a 4D array of objects and put all the values together like this. I wouldn't recommend it, but it does solve the problem,
I hear the curse of dimensionality lurking in the background, that said - first answer that comes to mind is:
final List<int,String> list = new List<int,String>();
then reviewing op's statement, we see two [][] which raises the question of ordering. Looking at two good replies already we can do Integer.toString( int ); to get concatenation which fulfills op's problem definition, then it's whether ordering is significant or flat list and ( again ) what to do with the second array? Is it a tuple? If so, how to "hold" the data in the row ... we could then do List<Pair<Integer,String>> or List<Pair<String,String>>, which seems the canonical solution to me.

Categories

Resources