-2

I am trying here to measure how many white spaces there are in text typed in a JTextArea. I am getting an outofbounds exception. Why so?

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        at java.lang.String.charAt(String.java:658)
        at ClassTest.main(ClassTest.java:11)





import javax.swing.*;
public class ClassTest {
    public static void main(String [] args) {
        JFrame frame = new JFrame();
        JTextArea textarea = new JTextArea();
        frame.setSize(300, 300);
        frame.add(textarea);
        frame.setVisible(true);
        String text=textarea.getText();
        int count = 0;
        for(int i=0;i>=text.length();i++) {
            char spacecount = text.charAt(i);
            if(spacecount==' ') {
                System.out.print(count++);
            }

        }

    }
}
  • 3
    `i>=text.length()` looks ... off. Should probably be `i < text.length()` – luk2302 Mar 07 '19 at 16:50
  • Possible duplicate of [What is IndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-indexoutofboundsexception-how-can-i-fix-it) – luk2302 Mar 07 '19 at 16:51
  • 2
    The `text` string is empty - see luk comment above. Ah, anyway this won't work. You'll pick the `JTextArea` text only a single time, before being able to write inside it – LppEdd Mar 07 '19 at 16:51
  • When `text` is empty, `text.length()` is `0`. When `i` is `0`, `i >= text.length()` is `0 >= 0` which is true, and you try to use `charAt(0)` on an empty string. As @luk2302 said above: The correct loop condition if looping forward is `i < text.length()`. – T.J. Crowder Mar 07 '19 at 16:52
  • well, you get an IndexOutOfBoundsException when accessing an array out of bounds, that is, using an invalid index (in this case 0 [see end of first exception line]) – user85421 Mar 07 '19 at 16:53
  • consider the `for` loop condition as being a while condition, that is, the loop is executed **while** the condition is `true` – user85421 Mar 07 '19 at 16:59

1 Answers1

0

I believe it should be < not >= for the 'for' loop condition.

Your for loop is as follows:

for(int i=0; i>=test.length();i++){

    char spacecount = test.charAt(i);

    if(spacecount==' '){
        System.out.println(count++);
    }
}

Let us take a walk through the for loop. The first part says, we create an int called i and initialize it to 0;

i = 0;

Next part says, keep looping while this condition is true. So it will loop while

i >= test.length()

The next part says, after each iteration, let us add 1 to i. The only reason it could possibly run is

if test.length() == 0; 
if test.length() == 1;

0 is not >= 1 so it won't run. That means, the only reason it could run is if the length is 0. Now if the string is of length 0, it would be "". What is the charAt(0)? Nothing. There is no 0 index. If the String were "a". Then charAt(0) would return "a". It is reaching for something that does not exist and therefore will not run. So one of the problems is that you need to change the condition to < instead of >=. Next, it is recommended to use camel case for fields (such as spacecount) which means you should change it to spaceCount. Lastly, it may not occur in this case but let us say, test = null. What happens? What is null.length()? Is that even possible? Well actually it will compile in the case that test = null; and then test.length() is executed. However, you cannot call such a method on a null value so you will get the dreaded runtime error, the "NullPointerException". This says, uh oh. We have a string that points to null. Well we cannot do anything with it. Here comes the exception. So in future code, it is recommended to be able to account for such cases. So what do we do? How do we check if a String == null? Well... String == null. So in the future, if it is possible for something to be null, put the for loop in an if statement that says:

if(test != null){

//put for loop here

} else{

//do something else
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gmanrocks
  • 261
  • 3
  • 12