add values in a array list - java

I have the following ArrayList
ArrayList<double[]> db_results = new ArrayList<double[]>();
Which is populated by the following loop
double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);
How can i add the values from the same position in each array to make another array??
So 1+1+1=3 would be position one of the new array 2+2+2=6 would be position two of the new array and 3+3+3=9 would be position three of the new array??
Cheers

A nested loop would do it.
I would encourage you to take the time to do a Java tutorial or read a textbook. This is really basic stuff, and you'd do better learning the language properly than learning by trial and error interspersed with random SO questions.
By the way, this line from your code won't compile:
double val = Double.parseDouble(i);
The i variable is declared as an int and the parseXxx methods take a String argument. To convert an int to double, just assign it:
double val = i;

This might be what you're looking for:
double[] newArray = new double[3];
for (double[] array : db_results) {
for (int i = 0; i < 3; ++i) {
newArray[i] += array[i];
}
}
It will work after db_results has been populated. You can also compute the sum array at the same time that db_results is being populated using slukian's method.

Either a java math function or a nested loop its for your answer. Try yourself its just a mathematical calculation.

Related

Math.random() and Random::nextInt always give the same exact number inside a for loop

So I am trying to make an Array with random numbers, but whenever I try Math.random or create a new Random object and use it, I always get the same number multiple times. My code is this one:
int[] Array = new int[size];
for (int Y : Array) {
Array[Y] = (int) (Math.random() * 10) + 3;
}
or this one:
int[] Array = new int[size];
for (int Y: Array) {
Array[Y] = rand.nextInt(30);
}
The output im getting is: [0][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3]
I haven't set a seed and I tried it outside the loop and inside but still only get the same number.
You are not referring to the index of the array, but to the specific element which remains the same. You have to use indexed loop.
Try with that (it is a good practice to use camelCase for variables, so 'Array' starting with small 'a')
int[] array = new int[size];
for(int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(30);
}

Java: Simple array splitting program

I am trying to make a simple Java program where you input 15 numbers (INTS, positive and negative) first, let's say these will get loaded into arrayOne. After that all numbers that are below '-5' need to be loaded into a second array (arrayTwo). I want to print all numbers of arrayTwo, while still retaining all arrayOne numbers.
I know my code doesn't make any sense at all, as I am still a beginner (about a month on and off). This is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int[] arrayOne = new int[15];
int count = 0;
System.out.println("Input 15 ints: ");
for (int i = 0; i <= arrayOne.length-1; i++){
arrayOne[i] = scanner.nextInt();
if (arrayOne[i] < -5){
count++;
}
}
int[] arrayTwo = new int[count];
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayOne[i] = arrayTwo[i];
}
}
}
}
It's so confusing for me. I don't know what to do to be honest. Do I need to use some kind of nested loop?
Thank you so much in advance, any help will be greatly appreciated.
int[] arrayTwo = new int[count];
int index = 0;
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo[index++] = arrayOne[i];
}
}
index will be used to write into the second array.
index++ is postfix increment operator. You can read about that here - Java: Prefix/postfix of increment/decrement operators?
You were doing the assignment the wrong way. It must be arrayTwo[..] = arrayOne[..] to assign a value from arrayOne into arrayTwo.
I know my code doesn't make any sense at all, as I am still a beginner
You don't need to apologize for being a beginner. We were all there once. Your code has the general right idea. You are just missing a few key concepts.
Look at this line:
arrayOne[i] = arrayTwo[i];
You are assigning values from arrayTwo into arrayOne. However, from what you say, you want it the other way around:
arrayTwo[i] = arrayOne[i];
But now you are assigning to the same index in arrayTwo as you are reading from in arrayOne. This will leave 0 values where the original values in arrayOne were larger than -5. I doubt this is what you want.
Instead, you should use two separate indexes for each array. Maybe i1 and i2. These will increment independently. That is i1 will always increment in the for loop because you are stepping over the elements of arrayOne. But i2 should only increment when you write a value into arrayTwo.
In arrayOne you have 15 integers.But in arrayTwo you have integers that are below -5.
Then you have to understand that size of the arrayTwo is less than(in many cases) or equal to size of arrayTwo.Reason is that the integers below -5 is a subset of integers.
Therefore using same iterator using while loop for two arrays will make an error.
instead using a second for loop , modify the code as below,
int indexArrayOne = 0,
indexArrayTwo=0;
while(indexArrayOne < arrayOne.length){
if(arrayOne[indexArrayOne] < -5){
arrayTwo[indexArrayTwo++] = arrayOne[indexArrayOne];
}
indexArrayOne++;
}
You can use a for loop like what you have done for this.The idea is you have to use two iterators for two arrays.
Use ArrayList for arrayTwo, so that you can hav all element in arrayTwo in just single for loop.
List<Integer> arrayTwo = new ArrayList<>();
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo.add(arrayTwo[i]);
}
}
you can use streams and lambda in this code.but first you have learn Stream API & lambda

Java method to multiply an ArrayList of decimal values by an array of doubles to get an array of ints?

Help! I have this school assignment that wants me to write a method to find the area of rectangles (an array of ints) by multiplying width (an ArrayList) by length (an array of doubles). I'm very very new to coding; I've tried for over five hours to get this working, but I keep doing things wrong and I simply can't get it right. This is the code for the method that I've written:
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
double temp = length[index];
for(index = 0; index < length.length; index++)
{
for(index = 0; index < width.size(); index++)
{
Object widthObj = (int)width.get(index);
area[index] = temp * widthObj;
}
}
}
The full starter code we were given is here, if you need more context (it's commented): http://pastie.org/pastes/916496
Thank you so much for any help you can give me in writing this method. I've been working for hours and I just can't get it...
The length of the array and size of the arraylist should be same , And you have to change the method logic a bit, Have a look at the below code snippet
public static int[] calcRectangleArea(List<Double> width, double[] length)
{
int[] area=new int[length.length];
for(int index = 0; index < length.length; index++)
{
area[index] = (int) (length[index]*width.get(index));
}
return area;
}
Call this method passing width arraylist and length array. It will return area array of ints
You dont really need two loops here. Assuming that width[1] correlates to length[1] you can just loop through both collections at the same time in the same loop.
This should work (i haven't written a line of java in ~2 years so it may not be 100%)
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
//assuming length.length == width.size
for(index = 0; index < length.length; index++)
{
int anArea = (int)(width.get(index) * length[index]);
area[index]=anArea;
}
}
again the code above assumes the size of the collections are the same.
Firstly, you don't need to assign temporary variables:
double temp = length[index];
...
Object widthObj = (int)width.get(index);
Since you will only reference them once. Reference them directly instead:
area[index] = length[index] * (int)width.get(index);
Secondly, your for loops are unneeded, and they are declared wrong. You're trying to increment the index (and twice nonetheless) that was passed to the function which will cause problems. If you were to use nested for loops, you would declare a new iterator variable for each of them:
for (int i = 0; i < something; i++) {
for (int j = 0; j < somethingElse; j++) {
doSomething();
}
}
However in this case you don't even need them.
In addition, you should not have created an Object when you wanted to cast an int:
Object widthObj = (int)width.get(index);
should have been
int width = (int)width.get(index);
However again, this line is unnecessary, and you shouldn't be casting to int this early.
Ultimately, all you need to do is the one line:
area[index] = (int)(length[index] * width.get(index));

Sqrt, and Math in Arrays

I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count

getting floats rather than objects out of an Arraylist

I am trying to create a method that removes duplicates from a 2d array. the outside array conains point indexes and the inner array contains their coordinates. It looks like i have to use an arraylist in order to remove elements without ending up with null values in the array. I would then like to convert the arraylist back into a 2D array in order to return it in the format i require. The problem is that the arraylsit contains an array of objects so i can't cast it into an array designed for floats. what is the correct syntax for filtering the floats from my array list. my code follows:
public class rem_duplicates {
public float [][] rem_geo_duplicates(float a[][]){
ArrayList<float[]> al = new ArrayList<float[]>();
float no_points = a.length;
int count = 0;
for (int i = 0; i < no_points-1; i++){
if((a[i][0] == a[i+1][0])&&(a[i][1] == a[i+1][1])){
a[i] = null;
count ++;
}
for (int j = 0; j < no_points; j++){
if (a[j] != null){
al.add(a[j]);
}
}
//how do i get the arraylist 'al' into this array b[][]?
float b[][] = new float [a.length-count][3];
b = al.toArray();
}
}
return b
}
Try using the following:
float b[][] = new float [a.length-count][3];
b = al.toArray(b);
This is the generic version of toArray() which in your case will return a float[][]. Keep in mind that float[] is an object, so there are no issues of boxing/unboxing here.
I notice several basic issues with your code however - I recommend trying to compile it and resolving the errors.
It works fine if you pass your newly created array as parameter:
float b[][] = new float[a.length-count][];
b = al.toArray(b);

Categories