Handling ArrayList out of bounds exception Java - java

My program will be creating a two dimensional grid / ArrayList. It will search for all boxes around a specific box and return their elements. However if the box is at an edge it may not have any surrounding boxes in the grid. So we will try to access an empty slot in an arrayList, possibly slot -1.
Is there anyway I can write some code like this in Java:
ArrayList arr = new ArrayList();
//add 5 elements to arr
for(int i = 0; i<10; i++){
if(arr.get(i) is out of bounds){
System.out.println("No elements here");
else{
System.out.println(arr.get(i));
}

You can check to see if i is outside the array bounds.
if i >= arr.size();
Though a better solution would be to loop over the contents of the array with a for each loop like so:
for (Object i : arr){
// Do something
}

You need boundary control check. For instance, if you need to loop around the neighbors of a point x, y, you could do
// assuming that you're checking around point x and y
// here you set minI, maxI
int minI = Math.max(0, x - 1);
int maxI = Math.min(listMax - 1, x + 1);
for (int i = minI; i <= maxI; i++) {
// here you set minJ and maxJ
int minJ = Math.max(0, y - 1);
int maxJ = Math.min(innerListMax - 1, y + 1);
for (int j = minJ; j <= maxJ; j++) {
// do your stuff here
}
}

Related

How can I decrease the brightness of a new image by 50 units in 2D arrays of String using if statement in Java?

import java.util.Arrays;
public class Combining {
public static void main(String[] args) {
int[][] imageData={{100,90,255,80,70,255,60,50},
{255,10,5,255,10,5,255,255},
{255,255,255,0,255,255,255,75},
{255,60,30,0,30,60,255,255}};
//First, we want to crop the image down to a 4x6 image, removing the right 2 columns. Declare and initialize a new 2D array of integers with 4 rows and 6 columns called `newImage`.
int[][] newImage = new int[4][6];
//Now that you have your empty image, use nested **for** loops to copy over the data from the original image to the new image, make sure not to include the cropped out columns.
for (int i = 0; i < imageData.length; i++) {
for (int j = 0; j < imageData[i].length - 2; j++) {
newImage[i][j] = imageData[i][j];
}
}
System.out.println(Arrays.deepToString(newImage));
//You want to decrease the brightness of the new image by 50 units. The way this works is that for every integer in the new 2D array, we will subtract the value by 50. Remember that the value range for the pixel is 0-255, so if the result tries to go below 0, just set it equal to 0.
if (imageData[i][j] - 50 < 0) {
newImage[i][j] = imageData[i][j] - 50;
} else {
newImage[i][j] = 0;
}
System.out.println(Arrays.deepToString(newImage));
}
}
Below is the question I have.
We want to decrease the brightness of the new image by 50 units. The way this works is that for every integer in the new 2D array, we will subtract the value by 50. Remember that the value range for the pixel is 0-255, so if the result tries to go below 0, just set it equal to 0.
Below is the hint to the question.
Remember to check if the value minus 50 is less than 0 when iterating through the elements of the new image: if(newImage[row][column]-50<0). If that condition is true, then set the element to equal 0 else subtract 50 from the element.
Below is code I have tried to solve the question.
//You want to decrease the brightness of the new image by 50 units. The way this works is that for every integer in the new 2D array, we will subtract the value by 50. Remember that the value range for the pixel is 0-255, so if the result tries to go below 0, just set it equal to 0.
if(imageData[i][j] - 50 < 0) {
newImage[i][j] = imageData[i][j] - 50;
} else {
newImage[i][j] = 0;
}
System.out.println(Arrays.deepToString(newImage));
}
}
I keep getting syntax error in the console that cannot find symbol i and j.
Combining.java:23: error: cannot find symbol
if(imageData[i][j] - 50 < 0) {
^
for the first part of your code
the for loop can be replaced with this
for (int i = 0; i < 4; i++) {
System.arraycopy(imageData[i], 0, newImage[i], 0, 4);
}
check the api for more detail about this method arraycopy
by the way your code will work but this is just another way
now for the issue
Combining.java:23: error: cannot find symbol
if(imageData[i][j] - 50 < 0) {
i and j in the for loop are only defined inside the loop body
local variable are defined and accessible only from where they defined so for example
int[][] newImage = new int[4][6];
for (int i = 0; i < 4; i++) {
System.arraycopy(imageData[i], 0, newImage[i], 0, 4); // only i defined here
}
\\here you can only access imageData and newImage but not i as i out of the scope
for local variable the scope determined by the { }
check this to get more details about variable scope
so either to define i and j outside the for loop like
int i, j = 0;
for (; i < imageData.length; i++) {
for (; j < imageData[i].length - 2; j++) {
newImage[i][j] = imageData[i][j];
}
}
or do the subtraction inside the for loop
for (int i = 0; i < imageData.length; i++) {
for (int j = 0; j < imageData[i].length - 2; j++) {
newImage[i][j] = imageData[i][j];
if (imageData[i][j] - 50 >= 0) {
newImage[i][j] = imageData[i][j] - 50;
} else {
newImage[i][j] = 0;
}
}
by the way the logic with your if is not right you should check the above version
also you can do it using that
newImage[i][j] -= 50;
newImage[i][j] = newImage[i][j] >= 0 ? newImage[i][j] : 0;

How to print only the last element of an array?

I am trying to print the last element of my array. The code can be seen below:
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
System.out.println(results[results.length - 1]);
}
However, when I attempt to run this, I get this result:
0.0 (printed 20 times in a row)
...
21034.782173120842
I do not know why it is printing out 20 zero's, and then the answer I want (21034.78). I thought that by doing results[results.length - 1], only the last element of the array would be printed. I have a suspicion that this has to do with the loop, but I do not know why or how to fix it.
Any help or advice would be greatly appreciated. Thank you!
You need to put the System.out.println outside the for loop, or else you will always print 0.0 because the last index of the array isn't filled yet.
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
}
System.out.println(results[results.length - 1]);
Output: 21034.782173120842
put your System.out.println , out of loop.
for(int y = 0; y < 21; y++) {
** YOUR LOGIC **
}
System.out.println(results[results.length - 1]);
You need to move the print statement outside the loop..
double [] results = new double[21]; double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
}
System.out.println(results[results.length - 1]);
You need to make a slight alteration. Here is one thing that you can do:
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < results.length; y++) {
results[y] = t;
t *= 1.04;
System.out.println(results[y]);
}
You can print the current index [y] each time through the loop. Or else you're always printing index 21 which isn't filled yet and will repeatedly print 0 until it is filled. The current iteration of the loop [y] will always be the last index that actually has a value in it, but the last index won't actually be filled with a value until your last iteration through the loop which explains your error here.

Shuffling an arraylist in java

Using an ArrayList, I need to subdivide a deck into two sections, one top section, and one bottom section. The top section will be the front of the ArrayList arr. If the size of the ArrayList arr happens to be odd, the top section size must be one more than the bottom section. Below you will see a few more specifications, there seems to be a slight logic error, but I'm having trouble figuring out where. As you can see, I have pretty much all of the code written and I feel as though this should be working. I need to shuffle without using collections.
for(int i =0; i<topHalf.size();i++){
topHalf.size() will return 0 because you have no elements in it yet. When you initialize it you are just allocating a size for the underlying array but the arraylist will have a size of 0...
As an aside you could use the sublist method.
// divide by two and round up
int middle = (int)(arr.size() / 2.0f + 0.5f);
ArrayList<Battleable> topHalf = arr.sublist(0, middle);
ArrayList<Battleable> bottomHalf = arr.sublist(middle, arr.size());
The easiest way is to use the 'sublist' method. You can do:
Double middle = Math.ceil(new Double(arr.size())/2);<br>
topHalf = arr.subList(0, middle.intValue());<br>
bottomHalf = arr.subList(middle.intValue(), arr.size());
The only change I would have made is adding a ternary operator to (simplify?) the code a little bit:
ArrayList<Battleable> topHalf = new ArrayList<Battleable>();
int topSize = arr.size() % 2 == 0 ? arr.size()/2 : (arr.size()/2)+1;
for(int i = 0; i < topSize; i++) {
topHalf.add(i, arr.get(i));
}
ArrayList<Battleable> bottomHalf = new ArrayList<Battleable>();
int count = topHalf.size();
int bottomSize = arr.size() - topHalf.size();
for(int i = 0; i < bottomSize; i++) {
bottomHalf.add(i, arr.get(count));
count++;
}
int x = 0, y = 0;
int end = arr.size();
for(int i = 0; i < end; i++) {
if(I % 2 == 0) {
arr.add(i, topHalf.get(x));
x++;
} else {
arr.add(i, bottomHalf.get(y));
y++;
}
}

Java Matrix how to assign int 1 or 0 to a 2D array? [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
Here is part of my code. I want to assign random number to the matrix population[][] first, then compare the random number to a specific number ranP, if population[][] < ranP, then re-assign population[][] to 1, otherwise 0. But it shows
arrayindexoutofboundsexception 0
Need help on the issue. Thanks!
randGen = new Random();
double randNum = randGen.nextDouble();
for ( int i = 0; i < 11; i++){
for (int k = 0; k < inipopulationsize; k++){
for (int j = 0; j < 25; j++){
ranP = 0.5;
//TMaxtrix[i][j] = matrix[i][j];
System.out.println(matrix[i][j] + " ");
population = new double[k][j];
System.out.println("randNum: " + randNum);
population[k][j] = randNum;
if (randNum <= ranP){
population[k][j] = 1;
}
else
population[k][j] = 0;
System.out.println("population: " + population[k][j]);
}//j loop
}//k loop
}//i loop
I am learning this by myself, and not taking any classes. If this really bothers you "experts", why dont you just ignore and save your time go home watching a movie or spending more time with your family? Appreciate the help from nice people here. But shame on you who only knows sarcasm. Here is what works finally:
randGen = new Random();
population = new int[inipopulationsize][25];
for ( int i = 0; i < population.length; i++){
for (int j = 0; j < population[i].length; j++){
double randNum = randGen.nextDouble();
ranP = 0.5;
if (i < 11){
//System.out.println(matrix[i][j] + " ");
}
if (randNum <= ranP){
population[i][j] = 1;
}
else
population[i][j] = 0;
//System.out.println("population index: " + i + " Dieasease index: " + j + " DI on (1) or off (0): " + population[i][j] + "");
}//j loop
}//i loop
Is the third loop because you want i 2d arrays? If so you should probably look at ArrayLists of 2d arrays.
int inipopulationsize = 25;
double[][] population;
Random randGen = new Random();
double randNum = randGen.nextDouble();
double ranP = 0.5;// outside loops
population = new double[inipopulationsize][25]; // out
for (int k = 0; k < inipopulationsize; k++){
for (int j = 0; j < 25; j++){
randNum = randGen.nextDouble();//i assume you want new random every time
if (randNum <= ranP){
population[k][j] = 1;
}
else
population[k][j] = 0;
}//j loop
}//k loop
System.out.println(Arrays.deepToString(population));
I don't see a reason for having 3 loops with a 2d array.
Random randGen = new Random();
double randNum;
for(int i=0; i<population.length; i++){
for(int j=0; j<population[i].length; j++){
randNum = ranGen.nextDouble();
if(randNum<0.5) population[i][j] = 0;
else population[i][j] = 1.0;
}//j loop
}//i loop
Your issue is that you are referring to an item outside the bounds of your 2D array.
Let's take a look at your code. This line: population = new double[k][j]; declares a new 2D arrays of size kxj. Then in this line: population[k][j] = randNum; you try to reference the item in the kth column and jth row of this same 2D array. This is not legal in Java arrays.
Java arrays are 0-indexed, which means with an array of size k, your indexes range from 0 to k-1. There is no item at index k. This is why you are receiving an index out of bounds error.
Please look at this link instructing you on the basic use of Java Arrays.
The exact error arrayindexoutofboundsexception 0 appears because on your first iteration, you create a population of size 0 by 0. Then you try to access the item in column 0 and row 0, that is to say, the first item. However as your population array has 0 size, it has no space, and even the index 0 is out of bounds.
However, I am not even sure this is what you want to be doing.
You are declaring a 2D array on each iteration of your loop. If all you are trying to do is make a single array of size inipopulationsizeby25 (these are the initial values of k and j) then you need to declare this outside of these two nested loops. Perhaps even outside of the third loop, as I am not even sure what that loop is doing.
Take a loop at anaxin's answer for how to effectively assign 0's and 1's to your population array randomly. (With randP set to 0.5 you are giving each a 50% chance of appearing.)

Rearranging array when it has a null position

I have this code that searches one object in an array and removes it. I'm having a problem with its position, since some other methods work with this array (and it gives me a NullPointerException every time). My method looks like this:
public void deleteHotel(String hotelName) {
for (int i = 0; i < this.hoteis.length; i++) {
if (this.hoteis[i].getName().equalsIgnoreCase(nomeHotel)) { //searches the array, looking for the object that has the inputted name
this.hoteis[i] = null; //makes that object null
if (this.hoteis.length > 1 && this.hoteis[this.hoteis.length - 1] != null) { //for arrays with lenghts bigger than 1 (since there's no problem with an array with one position)
for (int x = i; x < this.hoteis.length; x++) {
this.hoteis[x] = this.hoteis[x + 1]; //makes that null position point to the next position that has an object, and then that position points to the object in the next position and so on
}
this.hoteis[this.hoteis.length - 1] = null; //since the last to positions will be the same, make that last one null
Hotel[] hoteisTemp = new Hotel[this.hoteis.length - 1];
for(int x = 0; x < this.hoteis.length - 1; x++){ //create a new array with one less position, and then copy the objects on the old array into the new array, then point the old array to the new array
hoteisTemp[x] = this.hoteis[x];
}
this.hoteis = hoteisTemp;
}
i = this.hoteis.length;
}
}
}
When I use other methods (for example, one that returns the implemented toString()s of each object) it gives me a NullPointerException. Can you guys identify the error in the code? Much appreciated...
I have tested your function and I see what you mean by it getting a nullpointerexception, this is due to the array not resizing the list - which is due to your conditional:
if (this.hoteis.length > 1 && this.hoteis[this.hoteis.length - 1] != null).
Simply removing this solved the issue, here is the working function:
public static void deleteHotel(String hotelName) {
for (int i = 0; i < hotels.length; i++) {
if (hotels[i].getName().equalsIgnoreCase(hotelName)) { //searches the array, looking for the object that has the inputted name
hotels[i] = null; //makes that object null
for (int x = i; x < hotels.length -1; x++)
hotels[x] = hotels[x + 1]; //makes that null position point to the next position that has an object, and then that position points to the object in the next position and so on
Hotel[] hoteisTemp = new Hotel[hotels.length - 1];
for(int x = 0; x < hotels.length - 1; x++) //create a new array with one less position, and then copy the objects on the old array into the new array, then point the old array to the new array
hoteisTemp[x] = hotels[x];
hotels = hoteisTemp;
break;
}
}
}
Though please consider using a list of some sort when needing to use a list with a changing size.
The fundamental problem is that you're not allowing for where you removed the entry from the array.
Instead of
for(int x = 0; x < this.hoteis.length - 1; x++){
you want
for(int x = 0; x < this.hoteisTemp.length; x++){
(although that's a style choice)
and more significantly, instead of
hoteisTemp[x] = this.hoteis[x];
you want
int y = x < i ? x : x + 1;
hoteisTemp[x] = this.hoteis[y];
You also want to get rid of everywhere you're setting array elements to null, because if your copying logic works correctly, that's unnecessary.
For this use case, I would consider using one of the List implementations.
Consider rewriting your code
List result = new ArrayList();
for (int i = 0; i < this.hoteis.length; i++) {
if (!this.hoteis[i].getName().equalsIgnoreCase(nomeHotel)) {
result.add(this.hoteis[i]);
}
}
return result.toArray();
The point where you're shifting the array elements towards the left
for (int x = i; x < this.hoteis.length; x++) {
this.hoteis[x] = this.hoteis[x + 1];
}
The loop condition should be x < this.hoteis.length - 1 because at the last iteration when x = this.hoteis.length - 1 the index value this.hoteis[x + 1] would throw a NullPointerException.
Try using ArrayList it will simplify your code complexity.Here is the link to documentation.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

Categories