So I have two arraylists, one multidimensional and the other just an arraylist. I keep seeming to get an out of bounds error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at is15147029.main(is15147029.java:303)
And I have no clue why, what I am doing here is imputing integers from another array into the array list. I've checked that the array is full of integers but whenever I try to add the Integers into the arraylist I get an error.
ArrayList<Integer> selOrd = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> ordIndex = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < finalCost.length; i++) {
int lowCost = 0;
if(finalCost[i] > lowCost) {
lowCost = finalCost[i];
selOrd.add(0, finalCost[i]);
}
else if(finalCost[i] <= lowCost ) selOrd.add(finalCost[i]);
}
//Get Average Fitness Cost
for(int i = 0; i < finalCost.length; i++) total = total + finalCost[i];
avg = total/(finalCost.length);
//Sort into s1, s2, s3
for(int i = 0; i < selOrd.size(); i++) {
if(selOrd.get(i) > avg) ordIndex.get(0).add(selOrd.get(i));
if(selOrd.get(i) == avg) ordIndex.get(1).add(selOrd.get(i));
if(selOrd.get(i) < avg) ordIndex.get(2).add(selOrd.get(i));
}
The error seems to occur when adding the integers to selOrd.
Ant help would be appreciated, I also have a similar problem with another array list in my code. Thank you
The problem is most likely the result of hard coded index values.
Specifically get(1) and get(2).
You MUST verify that ordIndex.size() >= 3 in
order to safely execute get(2) and
ordIndex.size() >= 2 to safely execute get(1).
Also,
pay attention to error messages.
The exception clearly states index 1, size 1.
If the size of the array is one element, then any attempt to access the second element in the array (which has an index value of 1) must fail.
At first glance in your code, I don't see you adding anything to the ordIndex ArrayList of ArrayLists, so every get call to that will throw an exception.
Related
This seems trivial, but perhaps my understanding of Vectors is not what it should be. I'm getting [java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 1] on this code. The error occurs on line 3. Since the look is based on the size of the Vector, how can the array go out of bounds?
The method "getChangeSets()" returns a List. The List was originally created as a Vector.
2 for (int i = 0; i < getChangeSets().size(); i++) {
3 ChangeSet currentChangeSet = getChangeSets().get(i);
4 if (currentChangeSet.getSequentialNumber() == sequentialNumber) {
5 return currentChangeSet;
6 }
7 }
You would be better not using indexed iteration:
for (ChangeSet currentChangeSet : getChangeSets()) {
if (currentChangeSet.getSequentialNumber() == sequentialNumber) {
return currentChangeSet;
}
}
I suspect what is happening in your code is that getChangeSets() changes size between invocations, specifically getting smaller. The code above only invokes it once, before the first time the loop executes.
Please assign the changeset to a variable before iteration.
List<ChangeSet> list = getChangeSets();
for (int i = 0; i < list.size(); i++) {
ChangeSet currentChangeSet = list.get(i);
if (currentChangeSet.getSequentialNumber() == sequentialNumber) {
return currentChangeSet;
}
}
So for this extra credit problem in my calculus class, my other nerdy classmates and I decided that we would build a program to brute force a solution. One of these steps involves permutations. Through this algorithm, I managed to get it to work (I think):
public void genPermutations(int[] list, int k){
System.out.println("List: " + Arrays.toString(list));
System.out.println("----------------------");
if(k > list.length){
System.out.println("Not enough elements!");
return;
}
int[] counts = new int[list.length];
for(int i = 0; i < counts.length; i++){
counts[i] = 1;
}
int[] data = new int[k];
permutationHelper(list, counts, data, 0, k);
}
public void permutationHelper(int[] list, int[] counts, int[] data, int index, int k){
if(index == k){
//System.out.println(Arrays.toString(data));
permutations.add(data);
}else{
for(int i = 0; i < list.length; i++){
if(counts[i] == 0){
continue;
}
data[index] = list[i];
counts[i]--;
permutationHelper(list, counts, data, index + 1, k);
counts[i]++;
}
}
}
I have an ArrayList that stores all of the possible permutations (as integer arrays) that can be made from k elements of the list that I pass into the function. The problem is that if I print all of these permutations outside of the function, say after I call the genPermutations function, every permutation now is the same. But, when I print out the data where the comment is in the permutationHelper function, it correctly lists every possible permutation; I'm just unable to access them within the program later. My question is why are the values changing when I exit the function? Any help would be greatly appreciated.
Here are some pictures:
What is printed where the comment is.
What is printed later in the program.
The code used to print everything outside of the function is:
for(int i = 0; i < permutations.size(); i++){
System.out.println(Arrays.toString(permutations.get(i)));
}
I don't really know if that's necessary to know, but I just thought I'd include it just in case. Thanks in advance.
You're constantly modifying the same array object. Instead of adding different arrays to your list, you're in fact adding a reference to the same array over and over again.
To fix, instead of adding the data array to your list, you would have to add a copy of it, e.g. using Arrays.copyOf():
permutations.add(Arrays.copyOf(data, data.length));
Here the problem is that you are modifying the array after adding it to the list, you are modifying the same object again and again in different iterations. You were getting [3,2,1] in the list is because that was the outcome from last iteration. So as a fix you can use the following code. What it does is it will create a copy of data array and add that to the list.
int[] temp = Arrays.copyOf(data, data.length);
permutations.add(temp);
OR you can use clone() from array as follows.
int[] temp = data.clone();
permutations.add(temp);
I tried to make a simple roulette, however when I try to remove all data of a specific player (because they have lost all money) my game crashes and displays the error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at exam.Exam.main(Exam.java:330)
This is my line of code that crashes (I live in Denmark so the names are in danish):
Spiller is my Arraylist, antalSpillere is the amount of players,
denneSpiller is the specific data of a player I want removed.
for (int i = 0; i < antalSpillere; i++) {
Spiller denneSpiller = spillere.get(i);
if (denneSpiller.bank < 1){
spillere.remove(denneSpiller);
antalSpillereCheck ++;
}
else {
antalSpillereMedPengeIBanken ++;
}
}
The game crashes first when the for loop ends, and wouldn't crash if I removed the spiller.remove(denneSpiller);.
Indexing in Arrays starts from 0, so if you have 5 objects in array, the last one has index 4.
In your example you want to delete object on index 2 (third element), when you have only two in your array
Index: 2, Size: 2
.
Since antalSpillere decreases as you remove players, your for loop condition becomes invalid as some point. So you need to replace:
for (int i = 0; i < antalSpillere; i++)
with:
for (int i = 0; i < spillere.size(); i++)
spillere.size() will get updated as players are removed.
Here is the problem:
"Say you have an array for which the ith element is the price of a
given stock on day i.
If you were only permitted to complete at most one transaction (ie,
buy one and sell one share of the stock), design an algorithm to find
the maximum profit."
Here is my solution.
public class Solution {
public int maxProfit(int[] prices) {
int[] sell = new int[prices.length];
for(int i = 0; i<prices.length; i++){
for(int j = 0; j<i; j++){
sell[i] = Math.max(prices[i] - prices[j], sell[i]);
}
}
int sellPrice = prices[0];
int day = 0;
for(int i = 0; i<prices.length; i++){
if(sellPrice < prices[i]){
sellPrice = prices[i];
day = i;
}
}
int buyPrice = prices[0];
for(int i = 0; i<day; i++){
buyPrice = Math.min(buyPrice, prices[i]);
}
return sellPrice - buyPrice;
}
}
I'm not sure if it work, which is not a problem now. The problem is, it always shows Runtime Error at Line 9: (int sellPrice = prices[0];)
and
Line 18: (int buyPrice = prices[0];) as "java.lang.ArrayIndexOutOfBoundsException: 0".
So what's wrong with it? How to fix it? Thank you so much.
The only reason prices[0] would throw an AIOOBE is because the prices doesn't have any prices in it.
For example:
public static void main(String[] args)
{
int[] ints = new int[] {};
System.out.println(ints[0]);
}
Throws this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:7)
Whereas this, works.
public static void main(String[] args)
{
int[] ints = new int[] {93727};
System.out.println(ints[0]);
}
Check if you are not passing a zero length array to your maxProfit method and be sure to initialize the array before using it in your method.
Here is the possibilty:
ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
The array you passing to this method is empty. That is no elements in that array. The part
equal to the size of the array. (size is 0 and index is zero)
That is the cause in your case.
You're getting an exception probably because the prices array was not instantiated correctly.
Also, your algorithm is not guaranteed to be correct: consider the following set of prices,
$4, $5, $1, $3
The maximum profit made would be 2 dollars, but your algorithm would result in $1.
Here's some correct answers: Maximum single-sell profit
How does your main look like??
Make sure the array prices[] is created and also initialized.
If it is created like int[] prices = new int[] {}; you will see an error saying index out of bound.
Make sure you initialize (from user input or using hard coded values).
If it is from user input make sure that the values are assigned.
Hard Coded one will look like this:
int price[] = {100,200,500,2000,700,500,400};
Hope it helps
leetcode
When prices.lenght = 0, prices[] is null at line 9 and 18.
That's why you got errors.
I keep getting an IndexOutOfBoundsException when I run the executable. The first name and min_cost print before the error. I know that it is probably trying to access an index that can't be accessed. I can not figure out what is wrong.
for(int j = 0; j <= no_comps-1; j++){
String line2 = in.nextLine();
Scanner compline = new Scanner(line2);
int k = j-1;
String co_name = compline.next();
int x = compline.nextInt();
int y = compline.nextInt();
int val = compute(tot_boxes,my_boxes,x,y);
List <String> names = new ArrayList <String>(500);
names.add(j,co_name);
List <Integer> min_cost = new ArrayList <Integer>(500);
min_cost.add(j,val);
while(j > 1){
if(min_cost.get(j) > min_cost.get(k)){
Collections.swap(names, j, k);
Collections.swap(min_cost, j, k);
}
else{
}
}
System.out.println(names.get(j)+ " " +min_cost.get(j));
Thanks in advance for any help!
Edit:
DHL 46
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)
at java.util.ArrayList.add(ArrayList.java:426)
Edit: Now that you have posted the stack trace, please check if (min_cost.size()==0) as you are trying to access the second element 1 when the list size is 0.
I would suggest you to declare Lists outside for loop:
List <String> names = new ArrayList <String>(500);
List <Integer> min_cost = new ArrayList <Integer>(500);
for (...) {
// Your code
}
and use the list variables inside to access values.
What is happening right now is that you are creating new Lists every time the loop is executed. The problem starts when the value of j=2. You again create new Lists and assign values.
But then for j=2 your if (j>1) becomes true and you try to compare
if(min_cost.get(j) > min_cost.get(k))
You have initialized k as:
int k = j-1;
so for j=2:
k=1
And min_cost.get(k) -> min_cost.get(1)
But since you created new Lists inside for loop that value doesn't exist.
Hence, it throws IndexOutOfBoundsException.
Why are you recreating the names and min_cost objects within the loop? Whatever you add to the ArrayList will be gone each iteration of the loop. I'm guessing the Exception occurs when you try to call min_cost.get(k). Try putting these lines above the for-loop:
List <String> names = new ArrayList <String>(500);
List <Integer> min_cost = new ArrayList <Integer>(500);