-1

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)?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
A.Shetye
  • 113
  • 4

2 Answers2

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

So, when the loop stops, iis 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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

The error is in your name input.

Replace your input line with this code:

String name = sc.nextLine();
Safeer Ansari
  • 772
  • 4
  • 13
  • This seemed to fix the problem. But why does-String name = sc.next();-not work? – A.Shetye Nov 26 '17 at 11:51
  • Because lets say 'Akshat Abhay Shetye' was your input. sc.next() would get only 'Akshat' from your input and 'Abhay Shetye' would stay usless (untill sc.next() is called again). I hope it clears your confusion? – Safeer Ansari Nov 26 '17 at 11:56
  • Yep. But why does it work on the old BlueJ and Java?(my school PC) – A.Shetye Nov 26 '17 at 11:59