简体   繁体   中英

String Index Out of Bounds with charAt

As a school project, I have been asked to make a program that displays Initials of the name you enter( eg .for Akshat Abhay Shetye it would display AA Shetye).

This works fine on my school PC which runs a old bluej and Java but throws an error(StringIndexOutOfBoundsException: String index out of range) when I run it. This is my program:

import java.util.*;
import java.lang.*;
public class dispInitials{
    public static void main (String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your full name");
        String name = sc.next();
        //name = name.trim();
        String inName= name.charAt(0)+". ";
        int i = 1;
        for(i=1;i<(name.length()-1);i++){
            if(Character.isWhitespace(name.charAt(i)))
            break;
        }
        i++;
        inName=inName+name.charAt(i)+". ";
        for(i=i;i<name.length();i++){
            if(Character.isWhitespace(name.charAt(i)))
            break;
        }
        i++;
        System.out.println("The name is "+inName);
    }
}

Can anyone explain the error(at line 16)?

for(i=1;i<(name.length()-1);i++)

So, when the loop stops, i is equal to name.length - 1

Then, you're doing

i++;
inName = inName+name.charAt(i)+". ";

So you're trying to access the character at index name.length . But there is no such index. the last valid index is name.length - 1 . Hence the exception.

You need to learn to use a debugger and step through the code line by line, inspecting the values of the variables along the way. Or at least to add System.out.println() instructions in the code to diagnose your problems. This is basically a developer's daily job.

The error is in your name input.

Replace your input line with this code:

String name = sc.nextLine();

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