2D array filling | ArrayIndexOutOfBoundsException error - java

good afternoon! hi all! 1st time posting
for my assignment we are filling arrays using arithmetic and nested for loops. i've done a complete filling of a 2D array before using prime numbers, although i think i'm messing up somewhere..
when doing the line int priorNum = arr[r-1][c]; (see full code below) i run into an exception. i am trying to overwrite other lines in my array with this new equation, but must i be stopped by this utmost unchivalrous java error.
the error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
my array: int[][] arrayDimension = new int[10][6];
public static void populate2D (int[][] arr) {
//hardcode in values first :)
//and then peek up one row, but you can't go above the original row
arr[0][1] = 10;
arr[0][2] = 100;
arr[0][3] = 500;
arr[0][4] = 1000;
arr[0][5] = 5000;
int count = 0;
//for each row..
for (int r = 0; r < arr.length; r++) { //for each row
for ( int c = 0; c < arr[r].length; c++) { //for each column
arr[r][0] = count;
//never navigate out of bounds
//row 0 is where we're at.. how to populate further rows..?
int priorNum = arr[r-1][c];
int nextNum = priorNum * 2;
arr[r][c] = nextNum;
//can't look back .. SO go UP one.. which is r - 1 goes back one.. and then the length goes - 1
//when c is - peek UP a row < and enter last column.. ^
}
count++;
}
}
i left in some notes that i wrote if you can understand what i'm trying to go for :)
i can also offer this printArray method i wrote for any testing you'd like to try!
public static void print2DArray(int[][] arr) {
for ( int r = 0; r < arr.length; r++) {
for ( int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + "\t");
}
System.out.println();
}
}
}
thank you for any replies / assistance! everyone here seems very nice, i could not find my type of question that deals with my answer so i felt bad about posting hehe

The problem I can see is that in the first iteration when int priorNum = arr[r-1][c]; gets executed, r = 0, as specified by your outer for loop.
So you are basically trying to access an element of your 2D array using a negative index, which will result in an ArrayIndexOutOfBoundException being thrown.
You could adopt an if statement that will handle the first iteration so that you will not access a prior index.
You could also look at the Array access section of the following article:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
Hope this helped.

Related

How to resolve time out error in my java code

How to resolve timeout error in my java code:
This code first finds reverse of the element and then find out the difference between the actual and reverse value if that difference is divisible by k then increase the counter
Please find below code :
//all header files are included
public class Solution {
// Complete the beautifulDays function below.
static int beautifulDays(int i, int j, int k) {
int count=0;
for(int a=i;a<=j;a++)
{
int p=a;
int t=0,r=0;
while(a>0)
{
r=a%10;
t=t*10+r;
a=a/10;
}
if((t-p)%k==0)
count++;
}
return count;
}
// all other code of input and calling methods
You have an infinite loop in this section:
for (int a = i; a <= j; a++) {
int p = a;
int t = 0, r = 0;
while (a > 0) {
r = a % 10;
t = t * 10 + r;
a = a / 10; //OUCH!
}
}
Lets analyze this.
The outer loop increases the loop variable a by 1 from i to j
The inner loop decreases the same loop variable a until it reaches zero.
Guess which one wins? (Can't guess? Try a pencil and paper and "hand execute" these loops. It is a useful exercise.)
That means .... that the outer loop will never terminate.
Solution: use a different loop variable in the inner loop.

I'm trying to fill an array with integers by iterating, but I'm getting an ArrayIndexOutOfBoundsException

I'm trying to fill an array with integers using this code:
int[] steps = new int[1000001];
steps[0] = 0;
steps[1] = 1;
steps[2] = 2;
for(int i = 1001; i < steps.length; i++){
if(steps[i]==0){
steps[i] = steps[i-1]+1;
}
int current = i;
for(int m = current; m > 1; m--){
int mult = current*m;
if(mult<steps.length){
int suma = steps[current]+1;
if(steps[mult]==0){
steps[mult] = suma;
}
if(suma<steps[mult]){
steps[mult] = suma;
}
}
}
}
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(int k = 0; k < n; k++){
int q = scan.nextInt();
System.out.println(steps[q]);
}
scan.close();
And I'm getting this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2147479015
at javaapplication6.JavaApplication6.main(JavaApplication6.java:26)
C:\Users\User\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
But I can't see why this is happening. I understand that such an exception occurs when you try to access an index that doesn't exist. I've checked many times now my code and I haven't been able to find the issue.
Do you know what does this number mean? Because it is confusing me:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2147479015
NetBeans says the problem is at:
javaapplication6.JavaApplication6.main(JavaApplication6.java:26)
Line 26 is this one:
if(steps[mult]==0)
I think what that is saying is, that at some point, the program is trying to access a nonexistent index of the array. The thing is that I don't understand how that could happen here.
I put this line before to avoid that, but it seemed not to work:
if(mult<steps.length)
Then I modified that line by changing it to this one and it seems to work. It is not showing the exception anymore:
if(mult<steps.length && mult >=0)
Now the problem is that apparently, it does not get into this part of the code:
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(int k = 0; k < n; k++){
int q = scan.nextInt();
System.out.println(steps[q]);
}
scan.close();
I want to understand first, why that exception is occurring and why it is getting "solved" by adding that other part of the code, and second, why my code seems to get stuck in my first for loop.
I really would appreciate if you could please help me to understand those things.
Thanks in advance.
In your code you have
int mult = current*m;
where current and m is the size of the steps array
so 1000001 * 1000001 is going to exceed the size of the array and also exceed the max int value
I am not sure what logic you are wanting to do by doing
if(steps[mult]==0){
You problem can be shown with this code
int val = 1000000;
for (int i = 0; i < 100; i++) {
val = val * val;
if (val < 0) {
System.out.println(val);
}
}

Count characters in a multidimensional array, Java

Below is my code:
public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];
...
public void loadBombs()
{
//loadArray();
Random randomGen = new Random();
for (int u=1; u<=9; u++)
{
int randomRow = randomGen.nextInt(9);
int randomCol= randomGen.nextInt(9);
bombBoard[randomRow][randomCol] = "#";
}
//counting #'s -- setting variable
for (int d = 0; d < bombBoard[bombRow].length; d++)
{
for (int e = 0; e < bombBoard[bombCol].length; e++)
{
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
{
maxTurns++;
}
}
}
All I want to do is count the amount of (#)'s in the multidimensional array and assign it to a variable called maxTurns.
Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<
This line is equating the character # with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
Instead, access a single cell like this
if (bombBoard[d][e].equals("#"))
And initialize maxTurns before counting i.e. before your for loop:
maxTurns = 0;
You need to change the if codition
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
to
if (bombBoard[d][e].equals("#"))
You are using 2D Array, and do array[i][j] can populate its value for a gavin position.
do you want to count from the whole array or certain parts of the array only?
From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is
bombBoard[bombRow].length and bombBoard[bombCol].length
But if you want to iterate the whole array, think you should just use:
for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
{
if (bombBoard[d][e].equals("#"))
{
maxTurns++;
}
}
}

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Trouble assigning a value to an array in java

I don't know but for some reason an array refuses to change and i have no idea why. see further comments below
public static void contour (int[ ][ ][]image, int rows, int cols, int maxIntensity, int[ ][ ][]newImage) throws Exception
{
PrintWriter contour = new PrintWriter("contour.ppm");
int r = 0;
int c = 0;
int a = 0;
int sumk = 0;
while (r < rows && c < cols)
{
while (a < 3)
{
image[0][r][a] = newImage[0][r][a];
image[cols-1][r][a] = newImage[cols-1][r][a];
image[c][0][a] = newImage[c][0][a];
image[c][rows-1][a] = newImage[c][rows-1][a];
a++;
}
r++;
c++;
}
System.out.println (image[32][0][2]);
System.out.println (newImage[32][0][2]);
}
This code is a bit out of context, but you should be able to see which values I want to make the same in both arrays. The print statements are for testing purposes, and for some reason i get two different values. These arrays both have values assigned to them, but the image array will not change (and even when I create a new array in this method the same problem persists).
You can see that I define these arrays in the main method and they are as follows:
int image [][][] = readimage (fname, descriptor);
int newImage [][][] = new int [rows][cols][3];
So the image array is a returned array from a different method.
Am I overlooking something extremely obvious or what? I have been struggling with this for quite some time, so all hints, tips and explanations are greatly appreciated!!
Assuming you are traversing the columns and rows in the way you intend to...
You never reset the a variable to 0, so your code only works once.
int r = 0;
int c = 0;
int a = 0;
int sumk = 0;
while (r < rows && c < cols)
{
while (a < 3)
{
image[0][r][a] = newImage[0][r][a];
image[cols-1][r][a] = newImage[cols-1][r][a];
image[c][0][a] = newImage[c][0][a];
image[c][rows-1][a] = newImage[c][rows-1][a];
a++;
}
r++;
c++;
a=0; //<----ADD THIS
}
If either the rows parameter or the cols parameter is less than 33, then the location printed in your test will not be copied from newimage to image. The while (r < rows && c < cols) test causes the loop to terminate when the first of either r or c reaches its maximum value.

Categories