简体   繁体   中英

Assigning array variable inside of a loop

new to programming but trying to assign to my double variable inside my for loop. Basically I need to use Math.abs and Math.sin, which is sort of throwing me off. Any help is appreciated. If i need to provide any more information please let me know.

double[] xValues = new double[arrayAmount];
double[] yValues = new double[arrayAmount];

xValues[0] = minimumValue;

for (int index = 0; index==arrayAmount; index++)
{

    yValues = 20.0 * Math.abs((Math.sin(xValues))); // java saying this is wrong

}

Do you want something like this?

for (int index = 0; index==arrayAmount; index++)
{
   yValues[index] = 20.0 * Math.abs((Math.sin(xValues[index])));
}

Notice that you are getting a value from a specific index of xValues and saving at a specific index of yValues.

Also notice that your xValues only have 1 element. So if you code specify more about the values or the problem, we could be able to help you more.

Good luck!

The syntax in Java used to access to an element on an specific index of an array is:

nameOfArray[index]

so if you want to assign some value to yValues in an specific index, you have to use:

yValues[index] = 20.0 * Math.abs((Math.sin(xValues[index])));

Note that your loop won't work unless the length of the array is 0 . Try changing the loop condition to:

for (int index = 0; index < arrayAmount; index++) { ... }

or

for (int index = 0; index < yValues.length; index++) { ... } 

You need to specify an index to get/set specific values in an array.

If you have:

double[] xValues = ...;

And you want to refer to the double at index, say, 3:

xValues[3] = ...;
... = xValues[3];

You need to add [index] to your arrays.

Also, by the way, your condition is wrong in your for loop. The loop will go until the condition is true, not while the condition is true. You have:

for (int index = 0; index==arrayAmount; index++)

This says "loop while index==arrayAmount". You want:

for (int index = 0; index<arrayAmount; index++)

array is like rack on the shelf each have value block so instead of

yValues = 20.0 * Math.abs((Math.sin(xValues)));

put the value in each rack by yourself like this:

yValues[index] = 20.0 * Math.abs((Math.sin(xValues[index])));

now java does not says this is wrong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM