Checking if two sets of numbers are equal error - java

I'm getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
which is referring to this line in the code if(x[k]==y[j])
Scanner sc1 = new Scanner(System.in);
int [] x;
int [] y;
int size;
System.out.println("Numbers in launch code sequence should be entered on ");
System.out.println("single line, separated by blanks.");
System.out.println("");
System.out.println("Enter length of launch code sequence: ");
size = sc1.nextInt();
x = new int[size];
y = new int[size];
int k = 0;
int j = 0;
System.out.println("Mr. President, Enter the launch code sequence: ");
for(;k<x.length; k++){
x[k] = sc1.nextInt();}
System.out.println("Mr. Vice President, Enter the launch code sequence");
for(;j<y.length; j++){
y[j] = sc1.nextInt();
if(x[k]==y[j]){
System.out.println("All equal: Missile system cleared for launch.");
if(x[k]!=y[j]){
System.out.println("Codes do not check out. Abort missile launch.");
}
}
}
}

Your code
iterates through the x Array; afterwards, k == x.length
iterates through the y Array; inside this iteration, you compare with x[k], which is out of bounds for x
I guess what you really want to do is two nested loops - in that case, change
for(;k<x.length; k++){
x[k] = sc1.nextInt();}
to
for(;k<x.length; k++){
x[k] = sc1.nextInt();
and add the closing } after the y loop.

At this stage
if(x[k]==y[j]){
k has finished iterating through its array and will be set to x.length
and therefore out of bounds

You should reset the value of k back to 0 after you've done loading the code. Or you can just define it in the loop header.
for(int k = 0; k < x.length; k++)
{
// Your code here.
}

After this for loop finishes :
for(;k<x.length; k++){
x[k] = sc1.nextInt();}
value of k will be x.length
k == x.length //will be true. because the k will be incremented and the condition k<x.length will be checked. this is how the for loop functions
and in the next for loop you are accessing
x[k] // equivlent of x[x.length] which is out of abounds
The maximum index that you are allowed to access is x[x.length-1] because in java arrays the indexing starts from 0
Hence the Exception ArrayIndexOutofBounds, x[k] will be out of bounds

Related

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.

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.)

Creating a changing sequence of numbers in a for loop Java?

I'm trying to increment the following sequence in a for loop (Java):
1, 4, 9, 16, 25 etc the difference increasing by two each time. I tried using 'i+=3 + i' but I know that's wrong since it doesn't take into account that the variable i changes along the sequence.
Any help? Thanks
You could have an increment of i+=k and change k inside the loop in order to change the increment.
int k=1;
for (int i=1;i<1000;i+=k) {
k+=2;
}
If your i is changing, the simple logic is, use another variable that is declared outside the scope of the loop. This will make sure that it is not recreated everytime the loop runs.
int num = 1;
for(int i=1; i<maxValue; num+=2,i+=num){
//Use the value of `i` here, it will be as you wanted.
}
The sequence is to start with j=1 and k=4 and then derive next values of the series n times. The formula as follow:
Initial loop (i=0):
j = 1, k = 4;
Loop (i > 0 less than n):
Repeat below n times:
temp = k;
k = k + (k - j + 2);
j = temp;
print value of j being the series;
I assume that you take n as input from user and then generate the series nth times. Let's look at the following code example
int n = 10;
for(int i = 0, temp = 0, j = 1, k = 4; i < n; i++, temp = k, k += (k-j+2), j = temp) {
System.out.println(j);
}
Assuming that user inputs n = 10, the loop initializes i = 0 and continues until i < n is satisfied. It initializes j = 1 and k = 4 and then execute the body of the loop (printing j) followed by backing up the value of k, calculating new value for k and replacing the old value of j. The output for n = 10 is as follow:
1
4
9
16
25
36
49
64
81
100
Read Series number from the user and generate series based on given number.
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int ans;
for(int i = 1; i <= n; i++){
ans = i * i;
System.out.println(ans);
}

Java integer array, I cant do simple maths it seems

I have the code below:
int lines = 0;
while(lines < 2)
{
int[] oldarr = parr;
for(int i = 0; i < arrsize; i++)
System.out.print(" " + oldarr[i]);
System.out.println();
for(int i = 0; i < arrsize; i++)
{
if(i == 0)
parr[i] = 0;
else
parr[i] = Math.abs(oldarr[i] - oldarr[i-1]);
}
lines++;
}
parr is an array of integers of size [arrsize]. Each time through this loop I want to print the value of each index in parr, then set each index to the difference between the index before it and itself. Currently it gives me the correct (hardcoded) originally parr. But the next(first) iteration of changing parr gives me unexpected values; they are not even close to the difference between the two neighboring values..
Any ideas?
You aren't copying your array with this line:
int[] oldarr = parr;
The two variables are still pointing at the same array.
To get a copy, you can do:
int[] oldarr = Arrays.copyOf(parr, parr.length);
In your second for loop, you are setting the new value to the difference of the current value and the previous value, but the previous value was already changed in the previous iteration of the for loop.
Change your second for loop iteration to iterate through the array backwards, so your calculations don't depend on previous calculations.
for(int i = arrsize - 1; i >= 0; i--)

Array index out of bounds but shouldn't be

I'm making a pretty simple java-program and I get the following error (where n is a random number based on previous input from console):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: n
the line that is supposed to cause trouble is the if-statement here:
for(int i = 0; 0 < x; i++){
if(TalArray[i] < min){
min = TalArray[i];
}
}
the variable "min" is previously initzialized to TalArray[0] and is keeping track of the lowest number. All variables mentioned are int-variables
The correct code is...
for(int i = 0; i < x; i++){
if(TalArray[i] < min){
min = TalArray[i];
}
}
It's not clear what's the value of x in the code, but anyway the loop condition should look like this:
for (int i = 0; i < TalArray.length; i++)
Or like this, to avoid accessing the length at each iteration:
for (int i = 0, x = TalArray.length; i < x; i++)
The 0 < x comparison is mistaken: you're not modifying the value of x inside the loop, so the loop will either enter an infinite loop or not enter the loop at all, depending on the initial value of x.
The problem is, that your variable X is never changing so
your condition 0 < x is always true.
I guess the correct condition would be
for(int i = 0; i < x; i++)

Categories