array index out of bounds:7 [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public class mdar {
public void cont(){
Random rand = new Random();
int con = 100;
int multi[][]=new int [con][6];
for(int x = 0;x<multi.length;x++){
for(int y = 0;y<multi[x].length;y++){
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //this line is going bad
}
}
for(int i=0;i<multi.length;i++){
System.out.print("contester "+multi[i]);
for(int j=0;j<multi[i].length;j++){
System.out.println(" has "+multi[i][j]+" ");
}
System.out.println();
}
}
}
I deleted my old project and so i was trying to remake it and i can't figure it out anymore :S
Could someone help me out here?

The second dimention of multi is 6;
int multi[][]=new int [con][6];
However you call anything up to 8 on that second dimention
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //temp could be between 0 and 8 from the random function
As such you get an array index out of bounds, in your case temp was 7.
Addtionally your loop goes between 0 and multi[x].length-1
for(int y = 0;y<multi[x].length;y++){
But you call multi[x+1] which will at the end of the loop be one larger that the largest index of multi, but you'll hit this exception after the other one (99% of the time)
multi[x][y] = multi[x+1][temp];

I think you meant to write
multi[x][y] = temp;
//This would set multi[x][y] to a random int in the range [0,8] (inclusive)
instead of
multi[x][y] = multi[x+1][temp]; //this line is going bad
//This will assign the int value at multi[x+1][temp] to the variable multi[x][y]
There are 2 things wrong with this:
1) x is a for loop counter in range [0,multi.length) [inclusive, exclusive)
for(int x = 0;x<multi.length;x++)
x+1 is outside the bounds of the array
2) temp is a random int in range [0,8] [inclusive, inclusive]
int temp = rand.nextInt(9);
however the multi array is defined with a 2nd dimension size of 6 (valid locations multi[x][0] through multi[x][5])
int multi[][]=new int [con][6];
The random variable temp will be outside of the valid range 3/9 times (for 6, 7, 8), therefore you will encounter this error 33% of the time that nextInt(9) is called. Since it is called many times in a single call to cont() you will almost never have an execution that runs without error, however, it is still logically incorrect code whether it executes with or without error.

without an idea of what the code is supposed to do, it hard for us to give a solution. The error is quite clear. See in the last iteration of your outer loop x = multi.length - 1. So when you ask for multi[x+1][temp] you are asking for multi[multi.length] which is out of bounds since multi goes from [0 to multi.length-1].
In addition to that int temp = rand.nextInt(9) will also cause an out of bounds exception if it returns values 6,7 or 8, since the second dimension of multi must be in the range [0 to 5]
Again without an idea of what needs to be done, I can't know if the solution i propose below does what you want to do:
for(int x = 0;x<multi.length - 1;x++){
for(int y = 0;y<multi[x].length;y++){
int temp = rand.nextInt(multi[x+1].length);
multi[x][y] = multi[x+1][temp];
}
}

When your
int temp = rand.nextInt(9);
gives value as "7". You are getting this error. Debug and find.

You geting out of the length of the array, try to do this:
if(x+1 < multi.length)
{
multi[x][y] = multi[x+1][temp];
}

multi[x][y] = multi[x+1][temp];
at the end of loop x+1 making it.

You are declaring your 2D array with second dimension 6:
int multi[][]=new int [con][6];
Valid index of second dimension will be in range 0..5.
But then you access it with random number like 7 which is out of bounds:
int temp = rand.nextInt(9);
multi[x][y] = multi[x+1][temp]; //this line is going bad

int temp = rand.nextInt(9);
System.out.println(temp);
multi[x][y] = multi[x+1][temp];
here when temp goes beyond 5 it will give you exception as you have multi[][]=new int [con][6];
change the line int temp = rand.nextInt(5);
also you have another issue multi[x+1], when you have x=99 that time it will try to make 100 which is causing the issue, remember array index starts with 0

Related

Facing problem with the output of this code

My friend gave me this code and i cant seem to find the error in it. I am attaching the code below:
import java.util.*;
public class prg {
public static void main(String[] args) {
int n;
int count;
int a=0,b=1;
int c=0;
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
int ar[]=new int[100];
ar[1] = 2;
for(int i=3;i<=n;i+=2)
{
count=0;
for (int j = 2; j < i ;j++ ) {
if (i % j == 0) {
count++;
break;
}
}
if(count==0)
ar[i]=i;
}
for(int i=0;i<=n;i+=2)
{
a = b;
b = c;
c = a + b;
ar[i]=c;
}
for(int i=0;i<14;i++)
System.out.print(ar[i]+" ");
}
}
So, the even index is storing the fibonacci series and the odd index is storing prime number.
Problem: the rest of the code is working fine but the 9th index of 'ar' array is printing 0 i dont know why and because of it the output is showing wrong.
Take input n as 14 and check the code please.
Thankyou in advance.
PS: i have solved this question in one other way so i request you to not give answers like 'try my method, its not efficient'. I just want to know what is going wrong at INDEX 9 of the array.
Edited: facing problem with the Prime Number loop.
When i is 9, your code correctly identifies that it is not a prime number, so count is not 0. This causes this line to not run:
ar[i]=i;
And then you increase i by 2 to check the next odd number. This means that you never set index 9 of the array to anything, so it remains at its default value - 0.
To fix this, you should introduce a new variable possiblePrime to keep track of which number you are checking. Increase this variable every iteration of the outer for loop, and increase i only when possiblePRime is prime. Also, change the above line to:
ar[i] = possiblePrime;
9 is not a prime number, so it sets nothing in the array. 0 is the default value so it gets printed.

Prime Numbers Array in Java

I want to return an array that displays all the prime numbers within a certain range from 0 till whatever number I enter.
For the range from 0 to 5 I would like the array returned with [2,3,5]. Within the task I was told by my professor that I should fill the whole array with 0 before replacing those 0 wih prime numbers later.
Currently my code does not return the correct array as I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
My current result array is not [2,3,5] but [5,0,0,0,0].
Any help would be greatly appreciated.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
Arrays.fill(myAry,0);
for(int i=0;i<myAry.length;i++){
for (int nextprime=1; nextprime < bis; nextprime++){
int counter = 0;
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
System.out.print(myAry[i]+" ");
}
return myAry;
}
PS: I have a functioning method (istPrimzahl), which checks if a certain number is a prime number or not.
The problem is that your counter is in the wrong scope.
so instead of incrementing. on every iteration of the first for loop, you declare a new counter. so that it is 0 at the time u assign the prime number to the array.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
// Arrays.fill(myAry,0); // no need, this is already been done at initialization
for(int i=0;i<myAry.length;i++){
int counter = 0;
// adding <= 'nextprime <= bis;' to check also the last number in the range
for (int nextprime=1; nextprime <= bis; nextprime++){
// int counter = 0; wrong scope
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
if(myAry[0] != 0) // to get rid of displaying Zeros
System.out.print(myAry[i]+" ");
}
return myAry;
}
Put below line outside both for loop. That will work.
Reason for issue is - you are resetting the counter while entering the for loop.
int counter = 0;
ArrayList will be a better choice than array. However if using array is another school requirement, then what you have done:
int[] myAry = new int[size];
will already set all elements to zeroes.
There is also no need to use 2 loops for this. Just:
Loop through from 1 to n
if current number is prime, set it to array of current index
idx++
I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
That is because you are setting your counter variable back to zero in every iteration. You should declare it outside your loop.
Example:
int idx = 0; //place this outside the loop
for(int i=1; i<=n; i++)
if(isPrime(i))
myAry[idx++] = i;

Understanding Array code

I am learning java, I just want to make sure I am understand this line of code properly. It is as follows:
public class DataStructure {
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
The line I am not sure about is:
arrayOfInts[i] = i;
Is this saying that in the array, index 0 will produce an int value of 0, and index 2 will produce an int value of 2, and so on...?
Just to be clear, because I know this can be confusing, i is an int. By doing:
arrayOfInts[i] = i;
You are finding the i index. Where i is an int. So, if i is 7, it will be the 6th number of the array. Why not the 7th? Because it starts at 0:
(From the java docs)
So, lets say i is 7, right? It will be the 6th number. THAT IS IMPORTANT, and hopefully saves you lots of time with arrays.
Yes, you are correct. arrayOfInts[i] = i; means that at index i of the array arrayOfInts, the value is set to the integer i. So at index 0, it will have a value of 0; index 1 will have a value of 1 and so on. I hope this helps!
Rather than "produing" a value, as you stated, you are assigning a value to that index in the Array. If you were to go through the loop iteratively and wrote down each statement's outcome it would look like this if we use the logical statement arrayOfInts[i] = i
// first iteration
arrayOfInts[0] = 0;
i = i + 1;
// second iteration
arrayOfInts[1] = 1;
i = i + 1;
// third iteration
arrayOfInts[2] = 2;
i = i + 1;
So on and so forth. At the end of the iteration you will have a completely assigned Array that ends in the result
arrayOfInts = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
Also always keep in mind as you learn more programming techniques and languages that in computer science we start counting at 0 instead of 1. It took me quite a while to get that through my head.

Adding elements to array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
First off apologies if this is a simple question, but I am very stuck with it.
I need to create an array with a total number of elements, there is 14. I want to add each of the 14 elements to the array and was recommended doing this with a loop as I will be doing more tasks like this but with much more elements. I have tried this code so far but am having no luck;
int [] deviceID;
for(int i = 292; i <= 305; i++)
{
deviceID[i];
}
but I get the exception insert "AssignmentOperator Expression" to complete Expression.
So then I changed the line to
deviceID = deviceID[i];
Now I get a Type Mismatch: cannot convert from int to int[]
just to be clear I want slot 0 of the array have the value 292, slot 1 have 293........slot 14 have 305
Can anyone help me on this? What I thought would be basic and easy is turning into a bit of a nightmare for me.
You need to initialize array int[] deviceId = new int[20];
I guess you want to add 292 to 305 in array.
int [] deviceID= new int[14];//total element 14 (index 0 to 13)
int j=0;//counter which provides index during loop
for(int i = 292; i <= 305; i++)
{
if(j<deviceID.length)//chech whether j<14 as we want to add upto index 13
deviceID[j++]=i;//store i to the array at index j
//increments j to provide next index
}
I suggest you to read about Arrays from Java Doc it will clear all your dobts and bring some extra energy in you to start coding again.
I don't understand what you want to do, but if you want to have values from 292 to 305 in an array you should do:
int [] deviceID = new int[305];
for(int i = 292; i <= 305; i++)
{
deviceID[i] = i;
}
But it's really weird. What is your purpose ?
If you're trying to fill your integer array deviceID with those values of i, you'll need to first make sure the array is big enough, and then simply fill the array. Your problem was from trying to set your entire array equal to a single integer from one index (hence the type mismatch error).
int[] deviceID = new int[necessarySize]; // Creates an array with size "necessarySize"
int counter = 0;
for(int i = 292; i <= 305; i++)
{
deviceID[counter] = i; // Fills the array at index "counter" with value "i"
counter++;
}
If this is your entire array, then you'd only need (305-292)+1 = 14 spaces in your array.
DO THIS
int[] deviceId = new int[14]; //this creates a new array with size 14
int j=0; // for array index
for(int i = 292; i <= 305; i++)
{
deviceID[j] = i; //this inserts value of i at array position j
j++; //this keeps on adding 1 to previous value
}
You need to instantiate the array.
int[] deviceId = new int[sizeOfArray];
Where sizeOfarray, is an integer value indicating the size of the array.
Then to assign the position, you must use
deviceId[index] = value;
deviceID[i] just gets the i'th element in deviceID and does nothing with it.
deviceID = deviceID[i] is trying to assign an int to an object declared as a list, hence your error.
What you want to do is:
List<int> deviceID = new List<int>()
for(int i = 292; i <= 305; i++)
{
deviceID.add(i);
}
This should give you a list with only the numbers 292-305 in it

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.

Categories