简体   繁体   中英

Java String Error Out Of Bounds

I am exercising for my course in java and the task is to write a program which has the input of a list separeted with spaces. And the key is to turn the list around, ie put the first place on the last second on the one before last and truncate the negatives. But I am keep getting this error of StringIndexOutOfBounds. What seems to be the problem?

public static void main(String args[])
{ 
    Scanner in = new Scanner (System.in);
    System.out.println("Insert the list: ");
    String input = in.nextLine();

    String out = out(input);

    System.out.println(out);
}

public static String out (String input){
    String reverse = "";
    int counter = 0;

    while (counter<=input.length()){/*
        String min = input.charAt(counter) +                            input.charAt(counter+1);
        int num = Integer.parseInt(min) ;
        if ( num>=0 ){*/
            reverse+= input.charAt(counter);
            counter++;
        /*}*/
    }
    return reverse;
}

I suspect your StringIndexOutOfBounds comes from the fact you are iterating from index 0 to index input.length , so 1 too many.

For the sake of charAt the Strings in Java are 0-indexed, so you start counting from 0 (what you would call 'first' in plain English). In such a situation, the last character is at index length-1 .

So, to be specific. Your next thing to fix is the condition in the while loop. I think your intention was to say:

while (counter < input.length()) {
...

Any String has characters from index 0 to length-1. If you would try to do charAt(length), you would end up with StringIndexOutOfBounds.

Change the while line to below & it should work:

while (counter<input.length()){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM