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++)
Related
Take a look :
int[] v = new int[10];
for (int i = 0; i < v.length; i++) {
for (int j = i + 1; j < v.length; j++) {
if (v[i] > v[j]) {
aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
}
This works perfecly. But can someone explain how?
How this array DOES NOT goes out of bounds even if I start j with i + 1 ? How does this works?
You have confused the initialization with condition. The syntax for for loop() is-
for(initialization; condition; updation)
{
statement(s)
}
So even if you start j from 1 ( j = i+1 and initial value of i = 0), j will update only till it is equal to the length of the array v i.e., 10. So the moment, j = 10 ( when i = 9), the control will come out of j for loop() and when it will transfer to i for loop(), i will be updated to 10, thus meeting it's condition and moving the control out of i for loop() also.
I think you need to go back to basics on for loops
a for loop can be defined as for(before starting;continue when true;do at end of pass))
So it doesn't matter what your start value is, as soon as j is equal to v.length it will stop. It just does 1 less loop that if you started at i.
Your for loops are made up of a variable to keep track, the condition and the iteration. In your code, the condition of the for loops states that the variable that is keeping track cannot go past the length of v. Therefore, during the sort (because that's what the code is), the inner loop compares all of v's values using j as the index to swap if they meet the if condition. The outer loop is just there to make sure that each index of v is checked and are in the right place.
I have the following code from a previous past paper:
int n = arr.length;
double min = 0;
int minLocation=0;
for(int i = 1; i <= n; i++) {
if( arr[i] < min ) {
min = arr[i];
}
minLocation = i;
}
System.out.print("The minimal value is arr[");
System.out.println(minLocation + "] = " + min);
I have to answer the following questions from the code:
(i) The line on which the error appears
(ii) What effect the error would have
(iii) How the error should be corrected.
You may assume arr[] is a non-empty array of double values that has been
properly declared and initialized.
I know there will be a runtime error at the line with the if statement which i'm still not sure how. As I am unable to correct it I can't see how I get the undesired results. I can see it's such a straight forward question and I am missing out something extremely obvious but I have been looking at it for a while and i'm completely missing it.
There are several mistakes in that code. Here a list of them including explanation of impact and how to fix them:
You are initialising min with 0
Effect: If your array e.g. only consists of {1.1, 2.2} your code would claim that 0 is the minimum, what obviously is wrong because there doesn't exist an index i that arr[i] == 0
Fix: double min = Double.MAX_VALUE;
Your for-loop starts at index 1 for (int i = 1; ...)
Effect: You are skipping arr[0]
Fix: for (int i = 0 ...)
Your loop iterates once to often because of the condition or ( ... ; <= n; ...)
Effect: You will encounter an AIOOBE (ArrayIndexOutOfBoundsException)
Fix: for ( ... ; i < n; ...)
Your are overwriting minLocation in every iteration of the loop
Effect: After the last iteration of the loop, minLocation will always be = n
Fix: Place minLocation = i; inside the if-statement.
Corrected version
int n = arr.length;
double min = Double.MAX_VALUE;
int minLocation = 0;
for(int i = 0; i < n; i++) {
if(arr[i] < min) {
min = arr[i];
minLocation = i;
}
}
I know there will be a runtime error at the line with the if statement
which i'm still not sure how
This runtime error will be IndexOutOfBoundsException. This error occur because array index is one less than array size.
Your loop should be like.
for(int i = 0; i < n; i++)
Did you intend your for() loop to start at index 1? By convention it starts at 0;
It should really be: for(int i=0;i
Your for loop needs to be:
for(int i = 0; i < n; i++)
Otherwise you will get an IndexOutOfBoundsException since you access the array outside of its range.
Also you should change your min value initialiaztion to:
double min = Double.MAX_VALUE;
Otherwise you will only find the minimum if your array only contains negative values.
There are logical errors in your program, if it is intended to find the minimal value and position of given array.
Initialize
double min = arr[0];
End for loop at
i < n
Include
minLocation = i;
as
if( arr[i] < min )
{
min = arr[i];
minLocation = i;
}
Java array indices start at 0. So the for loop should be for( int i = 0; i < n; i++ ).
The minimum is only computed if the the elements of the array are non-negative.
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
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--)
I'm having a few problems while developing the following code in Java:
setPos(x, y);
for (int i = 0; x < size; i++) {
for (int j = 0; y < size; j++) {
if (board[x][y] == 'K')
{
System.out.println("You've found a key! CONGRATS!");
return true;
}
Eclipse notice me that i and j, as local variables, they're not used : The value of the local variable i is not used . If I change the i and write the x instead, it tells me that I'm repeating the variable.
j++ is tagged as dead code ?
Also, I have to search for a concrete type of element on the diagonal of a bidimensional array, I've been trying this with 2 for loops, as above, but no result yet.
Hope you can help me, thanks in advance!
Eclipse notice me that i and j, as local variables, they're not used
That's because you're not using them. You've assigned them values, and you've later incremented (added to) those values, but you've never used them for anything.
j++ is tagged as "dead code" (?)
For the same reason, the code increments the value of j, but j is never used, so the code does nothing. "Dead code" refers to code that has no purpose or which is never run.
Your loops don't make a lot of sense. For instance:
for (int i = 0; x < size; i++) {
Normally with a for loop, the control variable (i in this case) should appear in all three of the parts of the for statement (the initializer, the test, and the increment), like this:
for (int i = 0; i < size; i++) {
// Change here -^
But you're not doing that, you're only using i in the initializer and the increment, never in the test (x < size). The same is true of your loop with j.
Similarly, unless there's something changing the value of x, y, and/or size, then your loops will either never run (because x or y is already >= size), run once (because it happens that board[x][u] == 'K'), or they'll run forever (because x or y is < size and since nothing changes that, they just keep looping...).
Eclipse is giving you a hint where the error is:
for (int i = 0; x < size; i++) {
for (int j = 0; y < size; j++) {
you iterate over i and j, but you specify x < size and y < size as a condition. Thus you never actually use the i and j value, thus j++ and i++ is dead code.
If you really would like to use a loop, you should use the variable you use for iteration in the for-loop's condition:
for (int i = 0; i < size; i++) { // i instead of x
for (int j = 0; j < size; j++) { // j instead of y
Also, I have to search for a concrete type of element on the diagonal of a bidimensional array, I've been trying this with 2 for loops, as above, but no result yet.
Why not use a single for loop, like this:
for(int i = 0; i< size; i++)
if(board[i][i] == 'K')
{
System.out.println("You've found a key! CONGRATS!");
return true;
}
Look at this:
setPos(x, y);
if (board[x][y] == 'K') //no i or j so they are unused.
{
System.out.println("You've found a key! CONGRATS!");
return true;
}
If I change the i and write the x instead, it tells me that I'm repeating the variable.
Because x is already a variable(your function argument).so you can't declare it again.
dead code : Code that has no effect on programme.Dead code
Note:it's not a solution of your problem(because i don't know). it is just to show you the mistake.