I am new to Java and i am using eclipse for its compilation. I have seen many forums but i am not able to get around this error. I am creating a program for my homework and this is a small section of that program which is giving weird error. Any help is appreciated.
Here is where i am getting error -> aTwoD[i][j] = 0; <- at Initialize2D.<init>(Initialize2D.java:19)
I am stuck on this for quite some time now.
:-(
What is did ->
public class Initialize2D
{
private int[][] aTwoD;
public Initialize2D (int N)
{
System.out.println("N = " +N);
int counter = 0;
aTwoD = new int[N][N];
int i = 1;
while( i <= N )
{
int j = 1;
while( j <= N )
{
System.out.println("counter = " +counter);
aTwoD[i][j] = 0;
System.out.println("aTwoD["+i+"]["+j+"] = " + aTwoD[i][j]);
j++;
counter++;
}
i++;
}
}
public static void main( String[] args)
{
Initialize2D TwoDArray = new Initialize2D(2);
}
}
index starts from 0 so <= would cause out of bound
Array indices in Java start at 0, and end at length - 1. They don't start at 1 and end at length as your code assumes.
change
while( j <= N )
to
while( j < N )
In java indexing of N size array goes from 0 to N-1 including.
Beware that you iterate over i and j with the condition i <= N, j <= N.
Arrays in Java are zero based, meaning that they range between: 0 ... N-1.
If you access them with N that will be out of their range.
Change your iterator from i <= N to i < N (same for j). That should do the trick.
Related
In my program in certain function i have to fill 3x3 square of 9x9 array. At first glance it seems to be as trivial as it sounds but somehow one for() loop is not working properly. I asked two friends of mine and checked the code several times but still cant find any mistake everything seems to be working just fine if we do not count one for function. I tried to change it to other loop and it also didnt work. Below i give you my code and the outcome.I tried to serch the web for similar problem but also couldnt find one. Thank you in advance!
Code:
import java.util.Random;
public class ttabela
{
public static void main(String[] args) {
boolean bylo[] = new boolean[10];
int tabela[][] = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tabela[i][j] = 0;
}
}
wypelnianiePrzekatnych(bylo, tabela,0,2);
clear(bylo);
System.out.println("");
for(int i=0;i<3;i++) {
for (int j = 0; j < 3; j++) {
System.out.print(tabela[i][j]+" ");
}
System.out.println();
}
System.out.println("");
for(int x=0;x<9;x++)
System.out.print(tabela[0][x]+" ");
}
static int RandomBeetween ( int min, int max)
{
Random random = new Random();
int a1 = random.nextInt(max - min);
int a2 = a1 + min;
return a2;
}
static void wypelnianiePrzekatnych(boolean[] bylo, int[][] tabela,int i,int j){//i=0 j=2
int a = i,b=i ;
for (;a < (j+1);a++) { //This one doesnt make any difference
for (;b < (j+1); b++) {
System.out.println("p "+a+" "+b+" k");
tabela[a][b] = RandomBeetween(1, 10);
System.out.println(tabela[a][b]);
if (bylo[tabela[a][b]] == true) {
do {
tabela[a][b] = RandomBeetween(1, 10);
}while (bylo[tabela[a][b]] == true);
bylo[tabela[a][b]] = true;
System.out.println(tabela[a][b]);
}
else {
if (bylo[tabela[a][b]] == false)
bylo[tabela[a][b]] = true;
System.out.println(tabela[a][b]);
}
}
}
}
static void clear(boolean[] bylo)
{
for(int h=0;h<10;h++)
bylo[h]=false;
}
/*public static void wypelnianieReszty()
{
}*/
}
Outcome:
p 0 0 k
7
7
p 0 1 k
8
8
p 0 2 k
3
3
7 8 3
0 0 0
0 0 0
7 8 3 0 0 0 0 0 0
The problem is that your inner for loop will only execute once, so the outer loop has nothing to run after the first iteration.
I'll explain in more detail.
You start with:
int a = i,b=i ;
Let's say we passed in (..., 0, 2) as you have done. So a = 0, b = 0.
The outer for loop will run just fine exactly as expected - the code will run until a > (j+1) and there's nothing wrong here.
The problem is actually with your second for loop:
for (;b < (j+1); b++) {
For the first iteration, this will run as expected. But any time after that, it will never run - because you have already incremented b, such that b == (j+1).
I believe there is a fairly simple solution, assuming I've interpreted your requirements correctly:
int a = i;
int b;
for (;a < (j+1);a++) { //This one doesnt make any difference
b = i
for (;b < (j+1); b++) {
This works because it resets the value of b before each iteration of the for loop, so it won't halt immediately.
I hope this helps! Feel free to ask any questions in the comments.
Beginner here. I'm having problems running this series of for loops to find which integers are missing from an array.
public class FunWithArrays{
public static void main(String[] args){
String nString = args[0];
int n = Integer.parseInt(nString);
int inputArray [] = {1,2,4};
System.out.println(" The missing numbers are " );
findMissingNum(n, inputArray);
}
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= inputArray.length; i++){
int count = 0;
for( int j = 0; j < n; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
}
I get the answer I want, namely 3, however it doesn't print but rather shows up in a runtime error:
java.lang.ArrayIndexOutOfBoundsException: 3
at FunWithArrays.findMissingNum(FunWithArrays.java:17)
at FunWithArrays.main(FunWithArrays.java:9)
the method should take an input n from the user (when the program is run) as the largest value of the array and print all the ones missing
The logic is the outer for loop should traverse the array for numbers 1-n, and the inner loop should add to the count variable each time it finds a certain number. At the end of iteration it should print any numbers with a final "count" of 0. THIS IS LITERALLY DRIVING ME CRAZY!!! thanks in advance :)
First of all, you should traverse from 0 to (inputArray.length-1) index of inputArray. This will get rid of the ArrayIndexOutOfBoundsException, because java array indexing starts from 0 not 1.
And for inner loop, run from 0 to n, since n is the max number.
And Thirdly, it should be inputArray[i] == j, not inputArray[j] == i, same for printing the value. In you case I believe you have n>=4, so it was trying to access inputArray[3] via inputArray[j] call. That's why you are getting this out of bound error.
I think your code means like this: nest loop always run through inner loop first before run the outer loop.
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= n; i++){
int count = 0;
for( int j = 0; j < inputArray.length; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
I will just use a while loop instead:
int num =1;
while(num<=n){
for(int i = 0;i<inputArray.length;i++){
if(inputArray[i]!=num){
System.out.println(num);
}
}
num++;
}
The i incrementing to <= ipnutArray.length is not causing the error because i is never used as the index. What is causing the error is when n > length.
Also, you should not be checking n elements starting from the beginning because n is the max value, not the number of elements.
I'm trying to work out the difference in adjacent pairs of array elements, and then add the differences together, this is the method I'm using to do this.
I'm trying to split the original array into two smaller arrays and then subtract elements of the smaller arrays which will indirectly workout the difference of my initial array. the diffrences get stored on a last array which adds my differences together....
public static int changeinx(int array1[],int sum) {
int n = array1.length;
int y[];
int u[];
int c[];
c = new int [n/2];
y = new int [n/2]; // no. of arrays equal to 1/2 of array1, since two elements subtracted.
u = new int [n/2];
for(int i = 0 ; i < n ; i += 2 ) {
y[i] = array1[i];
}
for(int i = 1 ; i < n ; i += 2) {
u[i] = array1[i];
}
for(int i = 0 ; i < n/2 ; i++ ) {
c[i] = Math.abs( u[i] - y[i] ) ;
}
for(int r = 0 ; r < c.length ; r++ ) {
sum = sum + c[r]; //adding all the differences up, since abs has been taken
}
return sum ;
}
Why is this not working? :(
I find a major flaw in this loop:
for(int i = 0 ; i < n ; i++) {
int x = array1[i] - array1[i+1] ;
Let me give an example to illustrate this further, say we have an array
array1 = 25 15 55 12
the above loop at first iteration would do 25-15
in the 2nd iteration do 15-55
and 3rd iteration do 55-12
So now running this loop on an array of 4 elements would yield an array with 3 elements not at all conforming to your n/2 formula.
From my understanding of your problem I think your intention is to do 25-15 in the first loop
55-12 in the 2nd loop and end it, as to how you would go about doing it I leave it to you to figure out
This loop never ends:
for(int p = 0 ; p < n ; i++ ) {
y[p] = Math.abs(x); //trying to the difference as x, and asign to array y[]
}
Since p and n never change during the loop, if p < n is not true when the loop starts, it will never be true, and the loop will never end.
I'm trying to work out the difference in adjacent pairs of array elements, and then add the differences together, this is the method I'm using to do this.
If I understood the problem description correctly, this can be implemented much simpler:
public static int changeinx(int[] arr) {
int sumOfDiffs = 0;
for (int i = 0; i < arr.length - 1; i++) {
sumOfDiffs += Math.abs(arr[i] - arr[i + 1]);
}
return sumOfDiffs;
}
I have a java question.
I have two int[] arrays: cdn and cmn.
cdn is {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
cmn is {8,8,16}
I need a program that adds the consecutive integers of cdn[] upto cmn[init] and returns the number of integers used in the addition. Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. For the arrays above this is done 3 times: the first time the return value is 7, the second time it is 7, and the third time it is 16. The number of integers can be collected in and int[] which is {7,7,16}. The code I have is:
int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
for(int j = 0; j < cdn.length; j++){
plus += cdn[j];
numofints++;
if(plus == cmn[init]){
init++;
}
}
}
System.out.print(numofints);
in which m2 is the size of cmn, which is 3 in this case. Note that my program starts to loop from the beginning of cdn over and over again, because j = 0. I want it to start where it ended the previous time!
I hope you have a solution for me.
Bjorn
just pull j out of the outer loop, and use a while, instead of for, for the inner loop
and you also need to put plus = 0 into the loop
public class T {
public static void main(String[] args) {
int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] cmn = {8,8,16};
int numofints = 0;
int init = 0;
int m2 = 3;
int j = 0;
while(init < m2){
int plus = 0;
while(j < cdn.length){
plus += cdn[j];
j++;
numofints++;
if(plus == cmn[init]){
init++;
System.out.println(j);
break;
}
}
if (j == cdn.length) break;
}
}
}
Shoudln't if(plus == cmn[init]){ be if(plus >= cmn[init])? If you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break.
Is this code correct for perfect shuffle algorithm ? I'm always trying to generate a number from 0 to n and swapping the number with the last element in the array thereby reducing the range of n. However when the n=0, I get an exception. How do I deal with this case ?
int [] array ={1,2,3,4,5};
Random random = new Random();
int n=array.length;
while(n--!=0)
{
int number = random.nextInt(n);
int temp = array[n];
array[n] = array[number];
array[number] = temp;
}
EDIT: if I change it to --n >0 then it works correctly but am I implementing the shuffling algorithm correctly in that case because I never do anything for n=0 ?
In your code segment
while(n--!=0)
if n is 1, it will become 0 and `random.nextInt(0)` will return an error.
Refer this link
I don't think nextInt works if you pass an argument of 0.
The best way to shuffle is by using the Fisher Yates algorithm. It's fast, works in-place, and is unbiased:
int [] array = {1,2,3,4,5};
Shuffle(array, new Random());
// Fisher Yates shuffle - see http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
void Shuffle(int[] array, Random RNG)
{
for (int i = array.length - 1; i >= 1; i -= 1)
{
// get integer in range of j >= 0 && j < i + 1
int j = RNG.nextInt(i + 1);
//assert(j >= 0 && j <= i);
if (i != j)
{
// only swap if i and j are different
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}