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 A. A. 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)?
The error is in your name input.
Replace your input line with this code:
String name = sc.nextLine();