My program gives an index out of bounds error [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
int i=0;
while(!a.isEmpty()) {
if(a.toCharArray()[i]==' ') {
System.out.println(a.toCharArray()[i]);
}
i++;
}
When I run this program it's giving me an error: index out of bounds. How can I solve it?

You're not changing a in the loop, so a.isEmpty() will not change and you'll continue looping until i goes out of bounds. Did you mean:
while (i < a.length()) {
And as an aside, a.toCharArray()[i] can (and should) simply be a.charAt(i) (as #MartijnCourteaux also points out).

There are already a couple of answers that give solutions to the problem. This answer is about how you could have found the problem yourself.
Most array index out of bounds errors in loops are due to incorrect loop condition, so that the condition goes on being true even after the index has reached the end of the loop. Your loop condition did not depend on i, so the only way it could change from true to false is if a were changing inside the loop.
If you expected a to change, you should have put System.out.println(a) inside the loop, and monitored the value of a. You would have seen it not change.
Alternatively, if the isEmpty test were a typo, and you meant to test something that depends on i, desk checking your loop condition should have found it.

You should change your loop to this instead:
char[] c=a.toCharArray();
for(i=0; i<c.length; i++){

Related

Java insertion sort not working properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
enter image description here
This is the code screenshot link.
I am edit many time but every time the output is not completely sorted.
Your problem is very simply: you are increasing k far too often within your code!
Meaning: you are already looping with k; so you got:
for (int k=0; k < a.length; k++) { // dont use hardcoded "9" here btw!
and then you have
k++ again in the loop body. You simply dont have to do that!
Meaning: your k is growing faster than it should. But as your loop stops when k reaches 9; you are not processing all elements in your array!
Plus: insertion sort doesn't work with iterating your array once!
You have to keep iterating until all elements are in their place! You really want to study/think more about this algorithm. You, not us that is!
And as said, dont use hard-coded limits for arrays. You already say once that your array should contain 10 elements. From there on, you should be using a.length only! Besides: only use one-letter names for loop counters and such things. "a" is a pretty bad name for an array; why dont you call it "numbers" for example.

Can't create two int in for statement [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Can you please help me make the following code work?
for(int a=0, b=0; a<101; b<102; a++; b++;) {
stuff
}
You got the initialization (first) part of the loop right.
The termination or condition (second) part of the loop should be evaluated to a boolean, so assuming you require an AND relation between the conditions on a and b, it becomes a<101 && b<102. You might want || (OR) instead, depending on your logic.
The increment (third) part of the loop should contain comma separated expressions (same as the initialization part which you already got right).
I also removed an extra ';' from the end.
for(int a=0, b=0; a<101 && b<102; a++, b++) { stuff }

For loop unusual behavior in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
While i was writing code for an accounting application , i observed unusual behavior of List in java. After executing below code,
List<String> accountsList = new ArrayList<String>();
for(int i=0; i< (Integer.MAX_VALUE+2) ;i++){
accountsList.add("Account #"+i);
}
System.out.println("# of accounts in list : "+accountsList.size());
got output as - # of accounts in list : 0 , which was very interesting. Also code ran correctly without throwing any exception. If this is because of value overflow of int, why did not java throw warning/ exception.
Then i modified condition in for loop as, for(int i=0; i< Integer.MAX_VALUE ;i++) and code worked as expected.
Is this behavior has to do anything with Max value of int, as ArrayList can hold values till count of Integer.MAX_VALUE ( accountsList.size() returns value of type int, and int has max value defined).
You try this one
System.out.println((Integer.MAX_VALUE+2));
The output is -2147483647 that is less than 0 so no values will be added to your list.
When you try to go above MAX_VALUE, you'll get a large negative number due to overflow. Technically, there is nothing illegal about this code and the compiler/java will not throw a warning/exception before or at run time.

2D Array and a loop within an interval [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to crate a loop which sums the arrays values which are within the interval (for instance 2-5). My main problem is getting from the first checked value of the array to the next one and so on. Thankyou in advance.
int x=0,y=0,s=0;
int[][] myArray = { {0,1,2,3}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} };
Scanner scan = new Scanner(System.in);
int b = scan.nextInt();//lowest value
int c = scan.nextInt(); //highest value
if (myArray[x][y]>b || myArray[x][y]<c)
s=s+myArray[x][y]
//then check next one
if (myArray[x][y]>b || myArray[x][y]<c)
s=s+myArray[x][y]
You need to put these in a nested for-loop. Otherwise, they are executed only once, with x=0 and y=0. So all you are doing is essentially:
if (myArray[0][0]>b || myArray[0][0]<c)
s=s+myArray[0][0]
So s could only possibly be 0 or the first element in the 2D array.
Now, this conditional:
if (myArray[x][y]>b || myArray[x][y]<c)
does not mean what you think it means. This would evaluate to true for all numbers as long as b is less than c. For the semantics you are looking for, you want an AND operator (&&).

if inside a for whats wrong with it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
for(int i =0; i<8;i++){
for(int j =0; j<8;j++){
Ratsuk.getNewtablero().getMesa(i,j).setBackground(matrizcolor[i][j]);
if (Ratsuk.getNewtablero().getMesa(i,j).getBackground()==Color.lightGray);
Ratsuk.getNewtablero().getMesa(i,j).setEnabled(false);
}
}
Ratsuk.getNewtablero().getMesa(i,j) is for calling an a JButton 2d array that is inside newtablero and matrizcolor is a 2d array of colors of the same size.
when it runs this all the buttons in that array are disable not only the lightgray ones. Can any 1 explain me why?
You have a semicolon after the inner if-statement.
if (Ratsuk.getNewtablero().getMesa(i,j).getBackground()==Color.lightGray);
This causes the next line to execute every time. Remember that the compiler will associate either (1) a single statement or (2) a single block with any if-statement. In this case, the compiler is associating a single statement with that if-statement, but the single statement is merely a semicolon that literally does nothing. After the semicolon statement "executes", the program continues as normal by executing the next line:
Ratsuk.getNewtablero().getMesa(i,j).setEnabled(false);
Regardless of true or false value of the if-statement. Remove the semicolon and your problem will be fixed.

Categories