Array out of bounds exception for basic array [duplicate] - java

This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
How do I declare and initialize an array in Java?
(31 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
For some reason the size of my array is invalid and I am not sure how I should change NextIndex to fix this. The size should be dynamic and changing NextIndex to 1 doesn't help it.
/**
* Code for E7.9
* #Michael Goedken
*/
public class DataSet
{
// Implmentation
int nextIndex = 0;
double[] list = new double[1];
public static void main (String args[])
{
DataSet data = new DataSet(5);
data.add(3.5);
data.add(7.9);
data.add(15.2);
data.add(-7.3);
System.out.println("Sum: " + data.getSum());
System.out.println("Expected: 19.3");
System.out.println("Average: " + data.getAverage());
System.out.println("Expected: 4.825");
System.out.println("Maximum: " + data.getMaximum());
System.out.println("Expected: 15.2");
System.out.println("Minimum: " + data.getMinimum());
System.out.println("Expected: -7.3");
}
Constructs an empty data set.
#param maximumNumberOfValues the maximum this data set can hold
public DataSet(int maximumNumberOfValues)
{
double[] list = {maximumNumberOfValues};
}
Adds a data value to the data set if there is room in the array.
#param value a data value
public void add(double value)
{
list[nextIndex] = value;
nextIndex++;
}
Gets the sum of the added data.
#return sum of the data or 0 if no data has been added
public double getSum()
{
double sum = 0;
for (double i : list)
sum += i;
return sum;
}
Gets the average of the added data.
#return average of the data or 0 if no data has been added
public double getAverage()
{
double sum = 0;
double avg = 0;
for (double i = 0;i<list.length;i++)
sum += i;
avg = sum/list.length;
return avg;
}
Gets the maximum value entered.
#return maximum value of the data
NOTE: returns -Double.MAX_VALUE if no values are entered.
public double getMaximum()
{
double max = list[0];
for (int i = 1; i < list.length; i++)
{
if (list[i] > max)
{
max = list[i];
}
}
return max;
}
Gets the minimum value entered.
#return minimum value of the data
NOTE: returns Double.MAX_VALUE if no values are entered.
public double getMinimum()
{
double min = list[0];
for (int i = 1; i < list.length; i++)
{
if (list[i] < min)
{
min = list[i];
}
}
return min;
}
}

public DataSet(int maximumNumberOfValues) {
double[] list = {maximumNumberOfValues};
}
Here, list s a local variable declaration (and only has one element), which has nothing to do with the member variable of the same name.
Also this expression {maximumNumberOfValues} actually means "create an array with a single element with value maximumNumberOfValues"
Assign a value to the member variable instead, where that value is a new array with the desired number of elements:
list = new double[maximumNumberOfValues];

Change
int nextIndex = 0;
double[] list = new double[1];
to
int nextIndex = 0;
double[] list;
Change your constructor from
public DataSet(int maximumNumberOfValues)
{
double[] list = {maximumNumberOfValues};
}
to
public DataSet(int maximumNumberOfValues)
{
list = new double[maximumNumberOfValues];
}

I am not quite sure what your problem is.
int nextIndex = 0;
double[] list = new double[1];
I might be wrong... but your array is always the size of 1.
And as Ervin Szaligyi said -> you have to create the array differently

double[] list = {maximumNumberOfValues};
That's not how you create and allocate array in Java with the size of maximumNumberOfValues.
You should allocate it like this: double[] list = new double[maximumNumberOfValues];
Update: Also, double[] list = {maximumNumberOfValues}; should be declared like this in the constructor: list = new double[maximumNumberOfValues], otherwise you are declaring a local variable. You should declare list as private outside of your constructor.

Related

How to find the object with the highest value of an attribute? [duplicate]

Is there an easy way to get the max value from one field of an object in an arraylist of objects? For example, out of the following object, I was hoping to get the highest value for the Value field.
Example arraylist I want to get the max value for ValuePairs.mValue from.
ArrayList<ValuePairs> ourValues = new ArrayList<>();
outValues.add(new ValuePairs("descr1", 20.00));
outValues.add(new ValuePairs("descr2", 40.00));
outValues.add(new ValuePairs("descr3", 50.00));
Class to create objects stored in arraylist:
public class ValuePairs {
public String mDescr;
public double mValue;
public ValuePairs(String strDescr, double dValue) {
this.mDescr = strDescr;
this.mValue = dValue;
}
}
I'm trying to get the max value for mValue by doing something like (which I know is incorrect):
double dMax = Collections.max(ourValues.dValue);
dMax should be 50.00.
With Java 8 you can use stream() together with it's predefined max() function and Comparator.comparing() functionality with lambda expression:
ValuePairs maxValue = values.stream().max(Comparator.comparing(v -> v.getMValue())).get();
Instead of using a lambda expression, you can also use the method reference directly:
ValuePairs maxValue = values.stream().max(Comparator.comparing(ValuePairs::getMValue)).get();
Use a Comparator with Collections.max() to let it know which is greater in comparison.
Also See
How to use custom Comparator
This has been answered multiple time already, but since it's the first result on google I will give a Java 8 answer with an example.
Take a look at the stream feature. Then you can get the max form an List of Objects like this:
List<ValuePairs> ourValues = new ArrayList<>();
ourValues.stream().max(comparing(ValuePairs::getMValue)).get()
By the way in your example, the attributes should be private. You can then access them with a getter.
You should iterate over the list comparing/finding the max value O(N). If you need to do this often replace the list with a PriorityQueue O(1) to find the max.
Here fist and last is intervals between two indexes of arraylist you can also get for a complete list by removing them and i=0 upto size of float list.
// for min value
public String getMinValue(ArrayList list, int first, int last) {
List<Float> floatList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Float prova2 = ((Double) list.get(i)).floatValue();
floatList.add(prova2);
}
float min = Float.MAX_VALUE;
String minValue = "";
for (int i = first; i < last; i++) {
if (floatList.get(i) < min) {
min = floatList.get(i);
}
}
minValue = String.format("%.1f", min);
return minValue;
}
// for max value
public String getMaxValue(List<Object> list, int first, int last) {
List<Float> floatList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Float prova2 = ((Double) list.get(i)).floatValue();
floatList.add(prova2);
}
float max = Float.MIN_VALUE;
String maxValue = "";
for (int i = first; i < last; i++) {
if (floatList.get(i) > max) {
max = floatList.get(i);
}
}
maxValue = String.format("%.1f", max);
return maxValue;
}

Remove some percentage of elements from an array

I have an array of unknown length in java.
I want to remove 1 percent of the total elements of the array after sorting it.
How can I do that? If I pass an array and a length to a function.
public double deleteElements(double array[], int length) {
int trimmedLength = array.length-length;
for (int i = 0; i < trimmedLength; i++) {
}
}
I assume you mean something like :
import java.util.Arrays;
public class Test{
public static void main(String[] args){
double[] testArray = new double[]{0,1,2,3,4,5,6,7,8,9};
//implement sort, if needed
System.out.println(Arrays.toString( deleteElements(testArray, 5) ));
}
public static double[] deleteElements(double array[],int newLength){
//add check array != null
//add check length is <= array.length
double[] returnArray = new double[newLength];
for(int i=0;i<newLength;i++){
returnArray[i] = array[i];
}
return returnArray;
}
}
I made an assumption that the length you are passing in is the percent of elements you want to remove from the list.
This converts your array to a list, sorts it, and converts the remaining percentage back to an array which is returned.
public double[] deleteElements(double[] doubles, int length)
{
List<Double> elements = Arrays.stream(doubles).boxed()
.collect(Collectors.toList());
Collections.sort(elements);
int startElement = (int) (elements.size() / 100.0 * length);
List<Double> subList = elements.subList(startElement, elements.size());
return subList.stream().mapToDouble(d -> d).toArray();
}

"Missing return Statement" but I already have the return statement

/*
* One common programming activity is to find the minimum and maximum values
* within a list. In this challenge activity we will do just that. It will also
* demonstrate how arrays and for loops compliment each other nicely.
*
* First, execute the main() method as is so you can understand how the for loop
* works with the array. If you must, set a breakpoint and step through the code.
*
* Notice the min and max values are not correct. That's where you come in your
* job is to write these methods. Regardless of min or max, your approach should
* be the same: (Here's the pseudocode for min)
*
* set min to the value of the first element in the array
* for each element in the array
* if the current element is less than min
* set min to the current element
* end for
* return min
*/
package minandmax;
import java.util.Scanner;
public class MinAndMax {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
int[] array = new int[10];
// Read inputs into the array
System.out.println("Enter 10 Integers.");
for (int i = 0; i < array.length; i++) {
System.out.printf("Enter Integer %d ==>", i + 1);
array[i] = input.nextInt();
}
// Print out the array
System.out.print("You Entered :");
for (int i = 0; i < array.length; i++) {
System.out.printf("%d ", array[i]);
}
System.out.println();
// find the min / max and print
System.out.printf("Min = %d\n", getMin(array));
System.out.printf("Max = %d\n", getMax(array));
}
/**
* returns the smallest value in the array
* #param array array of integer
* #return integer representing the smallest
*/
public static int getMin(int[] array) {
//TODO: write code here
int min = array[0];
for (int a: array) {
if (a < min) {
min = a;
} else {
break;
}
}
return min;
}
/**
* returns the largest value in the array
* #param array array of integer
* #return integer representing the largest
*/
public static int getMax(int[] array) {
//TODO: write code here
int max = array[0];
for (int a: array) {
{
if (a > max) {
max = a;
return max;
}
I keep getting missing return statement and reach the end of file while parsing , however I already have my return statements and my code correctly closes brackets. Please help , thanks
In your getMax method, you get the error because return max is not reachable if (a <=max)
Looks at getMax, you have two open curly braces
public static int getMax(int[] array) {
//TODO: write code here
int max = array[0];
for(int a : array)
{
{ <===== HERE
if (a > max )
{
On a side note, you should not return max as soon as you encounter a number bigger than max, you should wait until you've looked at them all.
If the if condition is not at all true, Or if the control never goes into the forloop, then the method getMax() will not return anything. but as per the method definition, It should return an integer. And there are few braces which are not closed/openned properly.
Try this
public static int getMax(int[] array) {
int max = array[0];
for (int a: array) {
if (a > max) {
max = a;
}
}
return max;
}
Just think about what your code is realy doing in your 2 find methods.
you will never test all your int values in your array in that way you implemented this.
just test your values with a simple if(min < a) or if(max > a) and only return after your for() loop not in the loop.

How to get maximum value from double data type value set?

I get the five double data type values from five different function.Without adding those value into array is there any efficient java code for get the maximum value from that five value set.
double d1=r1.function1();
double d2=r1.function2();
double d3=r1.function3();
double d4=r1.function4();
double d5=r1.function5();
double[] d=new double[5];
for(int i=0:i<5;i++){
d[i]="d"+i;
}
double x=max(d);
public static double max(double[] t) {
double maximum = t[0]; // start with the first value
for (int i=1; i<t.length; i++) {
if (t[i] > maximum) {
maximum = t[i]; // new maximum
}
}
return maximum;
}
Without going this much effort is there any efficient way to get the maximum value from above double type data set? And also when adding value to the loop there also some error represent in d[i]="d"+i; part. Please provide me better solution.
You can use ArrayList<Double> and than
ArrayList<Double> alist=new ArrayList<Double>();
//Add double values to this list
You can use Collections.max(alist) to get maximum value and Collections.min(alist) to get minimun value.
Collections.max(Arrays.asList(d));
if would be more efficient if instead of having d as an array. have it as list to begin with.
You could use varargs instead of an array.
public double max(double... values) {
int max = -Double.MAX_VALUE;
for(double value : values) {
if(value > max) {
max = value;
}
}
return max;
}
Then you call your method like double max = max(d1, d2, d3, d4, d5);
EDIT :
Your lines
for(int i=0:i<5;i++){
d[i]="d"+i;
}
don't work, because "d"+i will create a String due to string concatentation and will not be the double variable with that name.
You cannot fill your array like this.
You will have to do:
d[0] = d1;
d[1] = d2;
d[2] = d3;
d[3] = d4;
d[4] = d5;
In Java 8:
Arrays.stream(darray).max().getAsDouble()
Full method (in our case, return zero if the array is empty; change your default as desired).
public static double max(final #Nullable double... values)
{
return ((values != null) && (values.length > 0)) ? Arrays.stream(values).max().getAsDouble() : 0;
}
This method can be called with either an array or varargs parameter:
double[] darray = new double[]{43.7, 65.2, 99.1, 87.6};
double max1 = max(darray);
double max2 = max(1.2, 3.4, 5.6);
You dont have to put them in array yourself, let Java do that part of work using varargs:
public static double max(Double... numbers){
double max = numbers[0];
for(int i = 0; i < numbers.length; i++){
if(numbers[i] > max){
max = numbers[i];
}
}
return max;
}
You can add d1,d2,d3,d4,d5 to TreeSet
Set<Double> set=new TreeSet<>(); // while you adding set will be sorted
// add values to set
List<Double> setAsList=new ArrayList(set); // convert set to list
System.out.println(setAsList.get(setAsList.size()-1)); // last value is the max
List <Double> d = new ArrayList<>();
d. add (d1);
d. add (d2);
d. add (d3);
d. add (d4);
d. add (d5);
Double max=Collections. max (d);
In Java 8,
java.util.Arrays.parallelSort(d).get(d.size-1)
to get max value in (merge sorted) array.

java array assignment - use of numeric literal

Create an application containing an array that stores 20 double values,
such as 2.34, 7.89, 1.34, and so on. The application should:
* Display the sum of all the array elements
* Display the average of all the array elements
* Display the largest value of all the array elements
This is a java class assignment. I got a bad grade on this one because my professor said I used a numeric literal. I lost 28 points out of 40. Did I design the solution so bad? His exact comments:
"The program you submitted uses numeric literals in place of the array’s length.
This cause several runtime errors when I change the size of your array and tested the code."
AND my solution:
import java.util.Random;
import java.util.Arrays;
public class MyArray{
public static double[] doubles;
public static void main(String args[]) {
MyArray.createDoublesArray();
MyArray.displayDoublesArray();
MyArray.displaySum();
MyArray.displayAverage();
MyArray.displayTheLargestValue();
}
/*Fill up the double Array class member*/
public static void createDoublesArray(){
doubles = new double[20];
//Create Random object
Random r=new Random();
double rangeMin = 1, rangeMax = 9;
//Generate random double number - 20 times within the range of 2 to 9
for(int i=0;i<20;i++) {
//Generate random double numbers and round them to the two decimal places
double randomdouble = Math.round((rangeMin + (rangeMax - rangeMin) * r.nextDouble())*100.0)/100.0;
doubles[i] = randomdouble;
}
}
/*Display the double Array*/
public static void displayDoublesArray(){
String delimiter;
Arrays.sort(doubles);
System.out.println("The double array: ");
// iterate through all the array elements
System.out.print("{");
for(int i=0;i<20;i++) {
if(i < 19){
delimiter = ", ";
}
else{
delimiter = "}";
}
System.out.print(doubles[i]+ delimiter);
}
System.out.println("\n");
}
/*Displays the sum of the double array.*/
public static void displaySum() {
//initialize the sum with 0
double sum = 0.0;
// iterate through all the array elements
for (int i = 0; i < doubles.length; i++) {
// add up each element to the sum variable
sum += doubles[i];
}
// display the sum
System.out.println("The sum is: " + Math.round(sum*100.0)/100.0 + "\n");
}
/*Displays the average of the double array.*/
public static void displayAverage() {
// initialize the sum with 0
double sum = 0.0;
// iterate through all the array elements
for (int i = 0; i < doubles.length; i++) {
sum += doubles[i];
}
// display the average by dividing the sum to the length of the array
System.out.println("The average is: " + Math.round((sum / doubles.length)*100.0)/100.0 + "\n");
}
/*Displays the largest value from the double array */
public static void displayTheLargestValue() {
//initialize the largest value with the first element
double largestValue = doubles[0];
//iterate through the remaining elements (ignore the first)
for (int i = 1; i < doubles.length; i++) {
// check if "i" element is greater then the current largest value
if (doubles[i] > largestValue) {
largestValue = doubles[i];
}
}
// display the largest value
System.out.println("The largest value is: " + largestValue);
}
}
I'm guessing that instead of things like the following
for(int i=0;i<20;i++)
he wanted you to use the length property
for(int i=0;i<doubles.length;i++)
additionally, here
//initialize the largest value with the first element
double largestValue = doubles[0];
you're assuming that doubles is not empty, and when it is empty, that will thrown an exception
To allow us to maintain this code easily I would 1st of all create:
private final static int SIZE = 20;
createDoublesArray:
public static void createDoublesArray(){
doubles = new double[SIZE];
//Create Random object
Random r=new Random();
double rangeMin = 1, rangeMax = 9;
//Generate random double number - 20 times within the range of 2 to 9
double randomdouble = 0.0; // <- we don't want to initiate double in 'for' loop
for(int i=0;i<SIZE;i++) {
//Generate random double numbers and round them to the two decimal places
randomdouble = Math.round((rangeMin + (rangeMax - rangeMin) * r.nextDouble())*100.0)/100.0;
doubles[i] = randomdouble;
}
}
displayDoublesArray:
/*Display the double Array*/
public static void displayDoublesArray(){
String delimiter;
Arrays.sort(doubles);
System.out.println("The double array: ");
// iterate through all the array elements
StringBuilder buff = new StringBuilder(); // use buffer
buff.append("{");
for(int i=0;i<SIZE;i++) {
if(i < SIZE-1){
delimiter = ", ";
}
else{
delimiter = "}";
}
buff.append(doubles[i]+ delimiter);
}
buff.append("\n");
System.out.println(buff.toString());
}
Our code seems a bit more generic and i can change SIZE (if needed) without actually change my code.
I agree with Maxim Shoustin...
Just one comment to add
1) It is not required to always use double. for eg.
double rangeMin = 1, rangeMax = 9; //can be replaced by int.
ref: Primitive Data Types

Categories