How to Fix the Runtime Error : java.lang.ArrayIndexOutOfBoundsException: 0 - java

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.

Related

IndexOutOfBounds ArrayList error

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.

Java - Improper Checking in For Loop

This is a chunk of code in Java, I'm trying to output random numbers from the tasks array, and to make sure none of the outputs are repeated, I put them through some other loops (say you have the sixth, randomly-chosen task "task[5]"; it goes through the for loop that will check it against every "tCheck" element, and while task[5] equals one of the tCheck elements, it will keep trying to find another option before going back to the start of the checking forloop... The tCheck[i] elements are changed at the end of each overall loop of output to the new random number settled on for the task element).
THE PROBLEM is that, despite supposedly checking each new random task against all tCheck elements, sometimes (not always) there are repeated tasks output (meaning, instead of putting out say 2,3,6,1,8,7,5,4, it will output something like 2,3,2,1,8,7,5,4, where "2" is repeated... NOT always in the same place, meaning it can sometimes end up like this, too, where "4" is repeated: 3,1,4,5,4,6,7,8)
int num = console.nextInt();
String[] tasks = {"1","2","3","4","5","6","7","8"};
String[] tCheck = {"","","","","","","",""};
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
for(int j = 0; j <=7; j++){
if(tasks[tNum].equals(tCheck[j])){
while(tasks[tNum].equals(tCheck[j])){
tNum = rand.nextInt(8);
}
j = 0;
}
}
tCheck[i] = tasks[tNum];
System.out.println(tasks[tNum]+" & "+tCheck[i]);
}
None of the other chunks of code affect this part (other than setting up Random int's, Scanners, so on; those are all done correctly). I just want it to print out each number randomly and only once. to never have any repeats. How do I make it do that?
Thanks in advance.
Firstly, don't use arrays. Use collections - they are way more programmer friendly.
Secondly, use the JDK's API to implement this idea:
randomise the order of your elements
then iterate over them linearly
In code:
List<String> tasks = Arrays.asList("1","2","3","4","5","6","7","8");
Collections.shuffle(tasks);
tasks.forEach(System.out::println);
Job done.
you can check if a certain value is inside your array with this approach.
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
boolean exist = Arrays.asList(tasks).contains(tNum);
while(!exist){
//your code
int tNum = rand.nextInt(8);
exist = Arrays.asList(tasks).contains(tNum);
}
}
if you are using an arraylist then you can check it with contains method since you are using an array we have to get the list from the array using asList() and then use the contains method. with the help of the while loop it will keep generating random numbers untill it generates a non duplicate value.
I used to created something similar using an ArrayList
public class Main {
public static void main(String[] args) {
String[] array = { "a", "b", "c", "d", "e" };
List<String> l = new ArrayList<String>(Arrays.asList(array));
Random r = new Random();
while(!l.isEmpty()){
String s = l.remove(r.nextInt(l.size()));
System.out.println(s);
}
}
}
I remove a random position in the list until it's empty. I don't use any check of content. I believe that is kind of effective (Even if I create a list)

java array from newboston lesson

While going over newboston java tutorial, I am looking at array lessons and wondering why assigning variable in array is ++freq[1+rand.nextInt(6)]. I understand the 1+rand.nextInt(6) part but ++freq, I do not.
Because I come from other script background, I would think freq[roll] = 1+rand.nextInt(6) is the right way(but clearly not right).. can someone explain to me why ++freq[1+rand.nextInt(6)] works here?
Another words,
Aren't I doing
freq[0] = 1+rand.nextInt(6);
freq[1] = 1+rand.nextInt(6);
freq[2] = 1+rand.nextInt(6);
------ continue till
freq[9] = 1+rand.nextInt(6);
??
class apples {
public static void main(String[] args) {
Random rand = new Random();
int freq[] = new int[7];
for ( int roll=1; roll < 10; roll++) {
//++freq[1+rand.nextInt(6)];
freq[roll] = 1+rand.nextInt(6);
}
It's for the increment of value of freq array positioned at the 1+rand.nextInt(6) index. What you're doing is assigning value 1+rand.nextInt(6) to freq[roll]. So you are replacing the value at the position not incrementing it.

Removing a chromosome from a population?

I am trying to write a method to remove a chromosome from my population. The method I have written is below. I am getting an out of bounds error when I run the code. Population is constructed with an ArrayList. The getChromosomeFitness method returns an int value score. Can someone spot my error?
void removeWorst()
{
int worst = population.get(0).getChromosomeFitness();
int temp = 0;
for(int i = 1; i < population.size(); i++)
{
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
{
worst = population.get(i).getChromosomeFitness();
temp = i;
}
}
Chromosome x = population.get(temp);
population.remove(x);
}
You should probably change
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
to
if (population.get(i).getChromosomeFitness() < worst)
You don't assure that in this line population has an element with the index 0:
int worst= population.get(0).getChromosomeFitness();
Try to add this to your method:
void removeWorst() {
if (population.isEmpty()) {
return;
}
...
There are several potential problems in your code:
int worst= population.get(0).getChromosomeFitness();
you need to make sure that population.isEmpty() is false
population.get(worst).getChromosomeFitness()
same thing, you need to make sure that (worst >= 0 && worst < population.size()).
The issue seems that you are getting the actual fitness rather than the object itself. The issue is with this line: int worst= population.get(0).getChromosomeFitness();. This is returning an integer value which is not related to the List's dimensions, as you said, it is the fitness of the chromozome, which could be well over the size of the list.
This should solve the problem:
void removeWorst()
{
int temp=0;
for(int i=1; i <population.size();i++)
{
if (population.get(i).getChromosomeFitness() < population.get(temp).getChromosomeFitness())
{
temp=i;
}
}
Chromosome x= population.get(temp);
population.remove(x);
}
That being said, a probably neater way of doing this would be to use a custom comparator to sort the list and then simply remove the last element.
Make sure population has something in it before trying to remove something from it?

Loop/array (Java)

I am having some problems in getting a loop to work. My goal is to create a loop which will allow the user to fill in lottery numbers in several rows (the user may decide how many rows he/she wants to fill out, but it can not be more than a maximum number specified earlier in the code). So far, my code is as follows:
import java.util.Scanner;
public class LotteryTicket {
public LotteryRow[] rows;
public int numberOfRows;
public Player ticketOwner;
public LotteryTicket(int maxNumberOfRows) {
this.rows = new LotteryRow[maxNumberOfRows];
}
Scanner input = new Scanner(System.in);
public void fillInTicket() {
System.out.print("How many rows do you want to fill in? ");
int n = input.nextInt();
while (n < 1 || n > rows.length) {
System.out.println("The number of rows must lie between 1 and " + rows.length);
System.out.print("How many rows do you want to fill in? ");
n = input.nextInt();
}
for (int index = 0; index < n; index++) {
rows[index].fillInRow();
}
numberOfRows = n;
}
When I try to run this in a main-method, and I enter a proper number of rows, I get the error message:
Exception in thread "main" java.lang.NullPointerException
at LotteryTicket.fillInTicket(LotteryTicket.java:24)
Line 24 is the line in which I call upon the fillInRow()-method which I have created in another class, so I suspect the problem lies here. I know that this method works fine, as I have tried it in a test program. However, am I not referring correctly to this fillInRow()-method?
Any help will be much appreciated!
You created an array with size maxNumberOfRows, but you haven't populated it with any objects. It initially just contains null references.
To fix the code, you have to call the LotteryRow constructor to create an object and then put a reference to that object in your array. You can fix your code like this:
for (int index = 0; index < n; index++) {
rows[index] = new LotteryRow();
rows[index].fillInRow();
}
You must create a new object and place it in the array before you call a method on it. Java arrays of objects are initialized to all nulls.
You never initialize rows. Yes, you create the Array with this.rows = new LotteryRow[maxNumberOfRows]; but that does NOT create a new LotteryRow Object for every Array Entry, so the whole array is filled with null. You have to create the LotteryRow Objects by yourself

Categories