I am trying to pass values into my array using a 2.4 increment over each iteration in my loop. Here is my code:
import java.util.*;
public class RunningArray {
public static void main(String[] args) {
double [] running = new double [10];
int i;
for (i=0; i<running.length; i+=2.4)
running[i]=i;
System.out.println(running[i]);
}
}
But when I try to print (running[i]) I am getting the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at RunningArray.main(RunningArray.java:26)
Can someone please explain why?
The loop counter is fine, the real problem is that because you haven't enclosed running[i]=i; in braces, that's the only statement in the for loop. You're printing running[i] outside the for loop, so i >= running.length (10 in this case).
Exception is self explanatory. value of i is going beyond array length of 10. Print the i value before accessing array value and you will know the issue.
Any reason for i = i+ 2.4?
At any point of time, i should not cross array length of 10.
It is because the variable i is of int type and each time you increment it by 2.4 only 2 is added to its value.
for (i=0; i<running.length; i+=2.4)
System.out.print(i+", ");
Output: 0, 2, 4, 6, 8,
but just before the condition of loop is tested to be false, i is incremented by 2 making its value 10.
when you write the following line without braces it takes the last value of i, that is 10
System.out.println(running[i]);
Since running[i] for i=10 is not available it gives exception.
Write it like this
for (i=0; i<running.length; i+=2.4)
{ running[i]=i;
System.out.println(running[i]);
}
Output:
0.0
2.0
4.0
6.0
8.0
Don't add 2.4 to the value of i, use another variable of double data type and increment it by 2.4 and store it in the array.
double [] running = new double [10];
double d=0.0;
for (int i=0; i<running.length; i++)
{
d+=2.4;
running[i]=d;
System.out.println(running[i]);
}
output:
2.4
4.8
7.199999999999999
9.6
12.0
14.4
16.8
19.2
21.599999999999998
23.999999999999996
you also are instantiating i as a int which means the .4 is being stripped each time. Initialize the variable to a double and it should carry the decimal point as you step through iterations.
double [] running = new double [10];
Double i;
for (i=0.0; i<running.length; i+=2.4)
{
running[i]=i;
System.out.println(running[i]);
}
Related
I am a long time java user diving into python.
I am searching for a way to create multi-dim arrays that may not have the same number of elements, some or all are NOT known until run time.
In java I'd assign a 3 dimensional array named runSet like this below:
double[][][] runSet = new double[5][][];
int randomInt = genRandInt(); // Returns a random integer between 0 and 101.
for(int i = 0; i < 4; i++) runSet[i] = getRuns(randomInt); // Returns double[randomInt][ToBeDetermined]
// ------------------------------------------------------------------------------
public double[][] getRuns(int num)
{
double[][] array2D = new double[num][];
for(int i = 0; i< num; i++) array2D[i] = genRandArray(); // returns double[] of random values with length between 0 and 1001.
return array2D; // Returns double[num][Varying Length]
} // end GetRuns()
No problems, this works just fine.
BUT using python I want to do the same, and I cannot figure out how to properly assign arrays with unknown number of elements. The best I have been able to come up with is:
import numpy as np
runSet = np.empty([5, ]) # <--- Does NOT throw an error.
randomInt = genRandInt() # Returns a random integer between 0 and whatever.
i = 0
while i < 4:
runSet[i] = getRuns(randomInt) # Returns [][] (double[randomInt][ToBeDetermined] in java speak)
i += 1
#-------------------------------------------------
def getRuns(num)
array2D = np.empty([num, ]) # <-- Does NOT throw an error.
i = 0
while i < num:
array2D[i] = genRandArray(); # Returns double[] of random values with a random LENGTH as well.
i += 1
return array2D; // Returns double[num][Varying Length]
# end GetRuns()
In genRandArray(), python version, I am returning with this (example random) statement:
return [12.4, 6.4, 8.0, 7.9, 8.2, 6.3, 8.8, 3.14, 2.345, 66.828, 12.0]
In both places I assign runSet[i] & array2D[i], I now know I'll get the error kind of like "sequential list being added to single ...."
Question 1): Maybe an array form is better for the return?
Question 2): Am I even close?
I have the feeling I may be going about this the completely wrong way, as the array thinking in python seems totally bass akward from the way I've been trained to think about it in java.
Thanks for any help!
Write a method named createDoubles that builds an array of floating point values that represent the squares of the numbers from 10.0 to 13.0, in steps of 0.5, inclusive of both boundaries. The method has no parameters and returns an array of doubles. There are exactly 7 numbers in this array.
I keep trying nut nothing is working. Thanks!
public static double[] createDoubles(){
double[] dArray= new double[7];
double[] squareArray= new double[dArray.length];
for(int i= 0; i< dArray.length-1; i+=0.5){
squareArray[i]= dArray[i]* dArray[i];
}
return squareArray;
}
If you are incrementing i with 0.5, how do you expect array index to work in loop? Can you please double check the code.
Something like this will work. Idea is that array indexes increment in steps of 1 and not 0.5 as your loop is expecting.
public static double[] createDoubles(){
double[] dArray= {10.0,10.5,11.0,11.5,12.0,12.5,13.0};
double[] squareArray= new double[dArray.length];
for(int i= 0; i< dArray.length; i++){
squareArray[i]= dArray[i]* dArray[i];
}
for(double f: squareArray)
System.out.println(f);
return squareArray;
}
Try the following way:
public static double[] createDoubles(){
double[] squareArray= new double[7];
double number = 10.0;
int i=0;
while(number <= 13.0) {
squareArray[i] = number*number;
number = number + 0.5;
i++;
}
}
return squareArray;
You can see the following demo:
int i = 0;
i = i + 0.5;
The i will always be 0.
That means your method will not stop when you invoke it.
Here's one way to do it, but probably not what the teacher wants:
public static double[] createDoubles() {
double[] answer = {10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0 );
// Actually, the above values should be 100,m ... 169.
// but I'm too laze to do the math
return answer;
}
Note that it is never a good idea to increment a loop index by a non-integer value. You might be surprised if you tried your method for increments of 0.1 instead of 0.5.
The reason this code isn't running but isn't working is because java is rounding down the i+=0.5 to i+=0, which is causing i to remain equal to 0, your loop never to exit, and your code not to do anything at all. To fix this part of your code, change the i+=0.5 to i+=1. However, as you do not declare anything in the square array, the resulting array that you return is nothing but 0s. Fix that by defining whatever you want in the d array, and multiplying those values together to create the values in the array you want to return. Or, you could simply declare put each value into the array like so:
for(int i= 0; i<= dArray.length-1; i+=1){
squareArray[i]= Math.pow(10 + (0.5*i), 2);
}
squareArray[integer+double] is not a valid array index.
Array index are always integer.
I'm trying to get a program to work where I generate 1,000,000 random numbers between 0 and 1 and then find and print the largest number.
I've got the generator to work and managed to insert each double generated into an ArrayList but I cannot seem to figure out how to find the largest number in the list. At the moment the current code throws the error "java.lang.IndexOutOfBoundsException".
This is all probably due to me being new to the ArrayList and not being fluent with its commands and how it works but I would really appreciate some help on what I'm doing wrong here as I've been stuck for a while.
import java.util.ArrayList;
import java.util.Random;
public class milran {
public static void main(String[] args) {
Random r = new Random();
ArrayList<Double> myList = new ArrayList<Double>();
for (int i = 1; i<=1000000; i++){
double randomValue = 0.0+(1.0-0.0)*r.nextDouble();
myList.add(randomValue);
}
double max = myList.get(1);
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
if (test>max){
max = test;
}
}
System.out.println(max);
}
}
First of all take a look at the docs for java.util.Collections and java.util.ArrayList.
Secondly, the ArrayIndexOutOfBoundsException is being triggered by this...
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
...
}
This is because array indexing starts at 0, therefore the last element is myList.size() - 1. In other words, when z = myList.size(), it is out of bounds.
Also, in your first for loop, you are using i = 1; 1 <= 1000000. It makes much more sense to use i = 0; i < 1000000 as you can use i to touch each element in an array (or list).
for( i = 0; i < 1000000; i++ )
{
// do something with myArray[i]
}
Here's what I would do after the values have been inserted...
Sort the array: Collections.sort(myList);
Retrieve the last element: System.out.println( myList.get( myList.size() - 1 ) );
...and that's it.
If you need to implement the actual sort yourself then i'd consider using a primitive double array (double[]) rather than a Collection.
Otherwise, if you are using a collection, you can use a foreach loop.
for( Double d : myList ) // for each Double 'd' in myList
{
// do something with d
}
N.B. Another potential issue with this line in the second loop
double test = myList.get(z);
This automatic conversion from Double (object) to double (primitive) is called unboxing. There will be a performance cost, especially when repeated a million times. In the first loop you are converting the other way (autoboxing) – also a million times.
ArrayList start count its elements from 0. You need to replace myList.get(1) to myList.get(0), int z=2 to int z=1 and z<=myList.size() to z<myList.size().
This line: for (int z=2; z<=myList.size(); z++) { is wrong. It should be for (int z=1; z<myList.size(); z++) {.
This is because arrays and lists are 0 based, so a list of size 2 has 2 elements - index 0 and index 1. Currently you try to index into the element number equal to the size, which does not exist.
Along the same line, myList.get(1); should be myList.get(0);.
This is unrelated to your problem, but this line 0.0+(1.0-0.0)*r.nextDouble(); can be much more easily written as r.nextDouble();. I'm not sure what you were trying to do by doing 0 + 1 - 0.
As others have already pointed out, you have an error in your for-loop condition that causes the index to go out-of-bounds.
One way that you can avoid this in the future is by using Java's for-each loop syntax instead of trying to manage the index yourself.
for (Double test : myList) {
if (test>max){
max = test;
}
}
This syntax makes your intent much clearer than the traditional indexed for syntax and removes a point of potential error (managing the index and the bounds of the list) from your hands.
I'm trying to create a method to randomly shuffle a array of primitives using a Arraylist. I was wondering if the .get(); method was the proper method to use on my Arraylist where on a normal array in a for loop it would just be array[j]; where j is the value in the for loop. Also, I'm not too familiar with Math.random(); and needed some help implementing it in this situation.
public static void selectionShuffle(int[] values) {
ArrayList<Integer> temp=new ArrayList<Integer>(52);
int rando=(int)Math.random()*52+1;
for(int counter=0;counter<temp.size();counter++){
temp.set(rando,(Integer)counter);
}
for(int counter=0;counter<values.length;counter++){
values[counter]=temp.get(counter);
}
}
Collections.shuffle(temp); is what you need
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List%29
What you may want to do is after creating the ArrayList, run a for-loop to add 52 values:
for(int i = 0; i < 52; i++){
temp.add(i);
}
Then do this:
Collections.shuffle(temp);
Print out the result to confirm
Your implementation should ensure that every index is set at least once. Your temp.set(rando,(Integer)counter) sets a random index to the value of counter. Also, you must change the value of rando with every iteration of the loop.
Math.random()
returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0.
as per Oracle, so when you multiply by 52.0 you get a value between 0 and 51.9 inclusive. When cast to an integer it is truncated to the floor of its value, giving you a range of 0 - 51 inclusive, or the size of your array.
So I got this assignment while my teacher is away, and basically I have to make a student project. The student has a name, marks, and average. To calculate the average I decided to store the marks inside a int[] array.
public void addQuiz(int m)
{
int l = (marks.length);
marks[l] = m;
}
int[] marks = new int[8];
But when I run the function:
student.addQuiz(90);
I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
Any help?
I'm not sure what the int[8] part does but it was in the tutorial I followed and it would give me a null pointer without it. There are eight marks in total so I just made it 8.
You can't dynamically add things to an array. You should use an array list instead.
Arraylist<Integer> marks = new ArrayList<Integer>();
then in your addQuiz method:
public void addQuiz(int m) {
marks.add(m)
}
You'll probably also need to change your method for calculating the average a bit, but that should be trivial and I'll leave it to you.
The error says: ArrayIndexOutOfBoundsException: 8
You have an array with 8 elements, indexed from 0 to 7 (inclusive). This array has a length of 8, and you are actually trying to access marks[8], when you only can go up to 7.
In Java, Array index starts from '0'. so, you cannot access the index of the array equal to the length of the array.if your arrays length is '8', then the last index of the array is '7' not '8'. if you are trying to access the illegal index of the array, then ArrayIndexOutOfBoundException is thrown. the code should be changed to
public void addQuiz(int m)
{
int l = (marks.length); //assuming marks is an array of length '8'
marks[l-1] = m; //index is 7 now
}
To calculate the average, you need to sum up the contents of the array (provided all the values are of int values) and then divided by the lenght of the array
int sum = 0;
int avg = 0;
for(int i=0; i<array.length;i++){
sum =sum+array[i];
}
avg = sum/array.length;
Hope this gives an idea
Use Arraylist<Integer> and then you can add to the list dynamically
There is not index in this array for this marks[l] = m;. use marks[l-1] = m;
You can call this for loop in main for getting marks 8 times.
for(int i=0;i<8;i++)
student.addQuiz(<marks you want to enter>, i);
You can define addQuiz function like below
public void addQuiz(int m, int arrayIndex)
{
marks[arrayIndex] = m;
}
int[] marks = new int[8]; //this will be as it is
These are minimal changes. You can make your code better by passing array marks to addQuiz as a parameter. But this will also work, its just that this is not the best way to write code.