Avoid going below index -1 with a for loop - java

How do I avoid going below 0 with this for loop ? When this loop executes, it checks if both the vehicle and the garage are in the same space. If not, it decrements the vehicle loop by --i to get the next available vehicle. when it reaches to index 0, it is going below index -1 causing the program to crash.
for (int i = vehicles.size() - 1; i >= 0;) {
for (int j = 0; j < garage.size();) {
if (this.garage.get(j).getSpace() == this.vehicles.get(i).getSpace()) {
if (this.garage.get(j).garageRequest(vehicles.get(i).getvehiclesType())
&& this.garage.get(j).getLimit() > 0) {
this.garage.get(j).addvehicles(vehicles.get(i));
this.vehicles.remove(i);
i--;
break;
} else {
j++;
}
} else {
i--;
j = 0;
}
}
i tried the following at the end
else if(i != 0) {
i--;
j = 0;
}

Add a second condition to your inner loop. That is, change
for (int j = 0; j < garage.size();) {
to
for (int j = 0; j < garage.size() && i >= 0;) {

Related

JAVA Numberline errors

I am trying to make the following number line is Java
2,3,5,7,11,13,17 (Prime Numbers)
I tried this code
for(int i =0; i <= 100; i++) {
if(i < 2) {
continue;
}
for(int j = 2; j < 1; j++) {
if(i % j == 0) {
break;
} else {
System.out.print(i + ",");
}
}
}
But it doesn't work
Anyone help please?
Your code is quite poor, but the minimal amount of changes needed to make it work yields this code:
outerLoop:
for(int i = 0; i <= 100; i++) {
if(i < 2) {
continue;
}
for(int j = 2; j < i; j++) {
if(i % j == 0) {
continue outerLoop;
}
}
System.out.print(i + ",");
}
But a further improvement would be to start the first loop at 2 right away:
outerLoop:
for(int i = 2; i <= 100; i++) {
for(int j = 2; j < i; j++) {
// and so on...
EDITED
There are a lot of errors in that code, first of all that second loop is a infinite loop and second one that the System.out.println line should not be in second loop it should be at end of first loop! If you place it in second it will print numbers hundreds of time.
This is the correct code :
for(int i = 2; i <= 100; i++)//begin loop from 2 instead of 0
{
boolean flag = true;
for(int j = 2; j < i; j++)
{
if(i % j == 0)
{
flag = false;
break;
}
}
if(flag)System.out.print(i + ",");
}
You need to set a flag to check if a factor was found outside the loop.

Summing cells from table

I seem to not be able to solve this java.lang.ArrayIndexOutOfBoundsException: 5
I understand the error, but the table is 5x5 and I think I have everything right for printing it.
public static int tulosta_matriisi(int[][] matriisi) {
int i=0, j=0;
for(i = 0; i <= 4; i++) {
for(j = 0; j <= 4; j++) {
if(j == 4 && i <= 4)
System.out.println(matriisi[i][j]);
else if(i <= 4 && j <= 4)
System.out.print(matriisi[i][j] +"\t");
}
}
return matriisi[i][j];
}
To avoid all this problem you have to use :
for(i = 0; i < matriisi.length; i++) {
for(j = 0; j < matriisi[i].length; j++) {
...
When you get out your loop, the i and j will be incremented so you should not return matriisi[i][j] this make this error java.lang.ArrayIndexOutOfBoundsException: 5, so instead you should to return matriisi[i-1][j-1] so in the end your program should look like this :
public static int tulosta_matriisi(int[][] matriisi) {
int i = 0, j = 0;
for (i = 0; i < matriisi.length; i++) {
for (j = 0; j < matriisi[i].length; j++) {
if (j == matriisi[i].length - 1 && i <= matriisi.length) {
System.out.println(matriisi[i][j]);
} else if (i <= matriisi.length && j <= matriisi[i].length) {
System.out.print(matriisi[i][j] + "\t");
}
}
}
return matriisi[i - 1][j - 1];
}
Good luck

Diagonal matrix check returns true for both non diagonal and diagonal

I am not sure where logically I am wrong. It returns true for both diagonal and non diagonal matrix. I am still new to 2d array and have watched video and read online. I do understand on how 2d array work but I am unable get the correct answer.
..
else{
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if((i != j) && (matrix[i][j] != 0)){
isDyg = false;
}
}
//System.out.print("");
}
isDyg = true;
}
return isDyg;
Because after your loop ends, isDyg is set to true everytime.
Change isDyg = false; to return false;
Or change your code to -
isDyg = true;
outerloop:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if((i != j) && (matrix[i][j] != 0)){
isDyg = false;
break outerloop;
}
}
//System.out.print("");
}
return isDyg;

Outer for loop begins from a certain position

public void removeDups() {
int i, k, j, lastFound = 0;
if (this.nElements < 1) {
System.out.println("Empty Array");
} else {
for (i = 0; i < this.nElements; i = lastFound) //outer loop
{
for (j = i + 1; j < this.nElements; j++) {
if (this.arr[i] == this.arr[j]) {
lastFound = i;
for (k = i; k < this.nElements; k++) {
this.arr[k] = this.arr[k + 1];
}
this.nElements--;
break;
}
}
}
for (i = 0; i < this.nElements; i++) {
System.out.println(this.arr[i]);
}
}
}
the previous method removes duplicates from the object invoking it (Array),the problem is that i want the outer loop to begin from a certain position every increment, i assign the value of that position to the variable lastFound and put that variable in the incremental part of the loop but the program goes to infinite loop and never stops, what is the problem with that?
You're setting i = lastFound at every iteration. At the start of the outer loop, initialize lastFound to i + 1. That way it will increment normally if you don't reset lastFound.
Alternatively, get rid of lastFound and when you find a match, set i = i - 1, start the k loop at i + 1 instead of i, and change the increment expression in the outer loop from i = lastFound to i++. I would also simplify your code by using System.arraycopy:
public void removeDups() {
if (nElements < 1) {
System.out.println("Empty Array");
} else {
for (int i = 0; i < nElements; i++) {
for (int j = i + 1; j < nElements; j++) {
if (arr[i] == arr[j]) {
System.arraycopy(arr, i + 1, arr, i, nElements - (i + 1));
nElements--;
i--;
break;
}
}
}
for (i = 0; i < nElements; i++) {
System.out.println(arr[i]);
}
}
}
Think of this: In first iteration,
i = 0
now if this is false: this.arr[i] == this.arr[j] then lastfound is never changed(remains 0), which will lead into infinite loop.
To fix the problem, handle the no match scenario.

Minesweeper game blocks around the mines

Hi so I'm building a program to create the classical minesweeper game in Java, and have almost everything down but I cant figure out how to check the sqaures around a mine and to write in the numbers (i.e. if there are one, two, three mines next to it). I only included the method it's under, but I can post the rest of the program if necessary. What should my approach be? Thanks!
private void countAdjacentMines()
{
for (int i = 0; i < mineField.length; i++)
{
for (int j = 0; j < mineField.length; j++)
{
if (!(mineField[i][j].getIsMine()))
{
mineField[i-1][j-1];
mineField[i-1][j];
mineField[i-1][j+1];
mineField[i][j-1];
mineField[i][j+1];
mineField[i+1][j-1];
mineField[i+1][j];
mineField[i+1][j+1];
mineField[i][j].setAdjacentMines(0);
}
} // end for loop rows
} // end for loop columns
} // end countAdjacentMines
Something like this:
private void countAdjacentMines()
{
for (int i = 0; i < mineField.length; i++)
{
for (int j = 0; j < mineField.length; j++)
{
if (!(mineField[i][j].getIsMine()))
{
int count = 0;
for (int p = i - 1; p <= i + 1; p++)
{
for (int q = j - 1; q <= j + 1; q++)
{
if (0 <= p && p < mineField.length && 0 <= q && q < mineField.length)
{
if (mineField[p][q].getIsMine())
++count;
}
}
}
mineField[i][j].setAdjacentMines(count);
}
} // end for loop rows
} // end for loop columns
} // end countAdjacentMines
For each item in that "list", do something like:
if ((i-1) >= 0 && (j-1) >= 0 && mineField[i-1][j-1].getIsMine()) {
numAdjacentMines++;
}
It's probably worth writing a helper function to do all of this, and then you just need to call it 8 times.
You're on the right track. You should be keeping a counter, that represents the count of adjacent mines that return true for .getIsMine().
if (!(mineField[i][j].getIsMine()))
{
counter = 0;
if (i-1 >= 0)
{
if (j-1 >=0 && mineField[i-1][j-1].getIsMine()) counter++;
if (mineField[i-1][j].getIsMine()) counter++;
if (j+1 < mineField.length && mineField[i-1][j+1].getIsMine()) counter++;
}
if (j-1 >=0 && mineField[i][j-1].getIsMine()) counter++;
if (j+1 < mineField.length && mineField[i][j+1].getIsMine()) counter++;
if (i+1 < mineField.length)
{
if (j-1 >=0 && mineField[i+1][j-1].getIsMine()) counter++;
if (mineField[i+1][j].getIsMine()) counter++;
if (j+1 < mineField.length && mineField[i+1][j+1].getIsMine()) counter++;
}
mineField[i][j].setAdjacentMines(counter);
}
You also need to be checking that all of those values (i-1, j-1, i+1, j+1) don't go outside the bounds of your array (i - 1 > -1, etc)
EDIT:: I think I covered all of the checks.
I'm not sure what you're trying to do. This statement, mineField[i-1][j-1]; and the ones like it just access data and do nothing with it.
I'm assuming that the array stores something that includes a boolean that tells you whether or not there's a mine in that space. If that's true, just make a counter and change those statements to something like if(mineField[i-1][j-1].hasMine()) counter++;. And then change the last statement to mineField[i][j].setAdjacentMines(counter);.
int sum = 0;
sum += mineField[i-1][j-1].getIsMine() ? 1 : 0;
sum += mineField[i-1][j].getIsMine() ? 1 : 0;
sum += mineField[i-1][j+1].getIsMine() ? 1 : 0;
sum += mineField[i][j-1].getIsMine() ? 1 : 0;
sum += mineField[i][j+1].getIsMine() ? 1 : 0;
sum += mineField[i+1][j-1].getIsMine() ? 1 : 0;
sum += mineField[i+1][j].getIsMine() ? 1 : 0;
sum += mineField[i+1][j+1].getIsMine() ? 1 : 0;
mineField[i][j].setAdjacentMines(sum);
This is count up how many are mines and use it properly. It may be more clean to create a loop to perform this calculation, since it is the same thing for each adjacent field.
Try something like:
private static int countAdjacentMines(int x, int y) {
int adjacentMines = 0;
for(int i = -1; i <= 1; i++) {
if((x + i < 0) || (x + i >= width)) {
continue;
}
for(int j = -1; j <= 1; j++) {
if((y + j < 0) || (y + j >= height)) {
continue;
}
if(mineField[x + i][y + j].getIsMine()) {
adjacentMines++;
}
}
}
return adjacentMines;
}
This should count the number of mines neighbouring a block at (x, y).

Categories

Resources