haasbury
haasbury

Reputation: 13

Error while running, works fine on the build

First, this is for a school class. This is my program:

import java.util.*;

public class Exitearly1 {
    public static void main(String[] args) {
        Scanner kbinput = new Scanner(System.in);
        System.out.println("Please input your name: ");
        String name = kbinput.next();
        int count = 0;
        while (count < name.length()) {
            count++;
            int res = name.charAt(count);
            if ((res == 'a') || (res == 'A'))
                continue;
            System.out.println(name.charAt(count));
        }
        System.out.println("Name with no A's");
    }
}

It prints what I am inputting (Andrea) without A's like it is suppose to, but after doing so instead of printing out that last line it gives me this in the output:

n
d
r
e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
    at java.lang.String.charAt(String.java:686)
    at Exitearly1.main(Exitearly1.java:13)

I tried many different ways to fix it with nothing changing it, I am coming here because I asked my teacher how to fix it, and she only told me what was wrong with it which I already knew.

Upvotes: 0

Views: 71

Answers (2)

Sirs
Sirs

Reputation: 1297

You're iterating from position 1 to position name.length(), so you're going out of range (since stringvar.charAt(stringvar.length()) always results in an out of range exception.

Orel's solution will probably end in an infinite loop. You should do something like this:

while (count < name.length())
{       
    int res = name.charAt(count);
    if (( res !='a')&&(res !='A')) {
      System.out.println(name.charAt(count));
    }
    count++;
}

Please note that your code never shows the first position of the String, independently of it being an 'A' or anything else.

Upvotes: 2

Pshemo
Pshemo

Reputation: 124235

While others pointed out your mistake (you increased counter before you used it to read character at position described by it) I would suggest to use enhanced for loop (it can iterate over arrays, or instances of classes which implements Iterable interface ), something like

for (char ch : name.toCharArray()){
    if ((ch == 'a') || (ch  == 'A'))
        continue;
    System.out.println(ch);
}

Upvotes: 1

Related Questions