Nikhil Gopal
Nikhil Gopal

Reputation: 107

Java program involving substring() and charAt() methods

My program is supposed to print out the initials of the name and print the last name. Eg. if the name entered is Mohan Das Karamchand Gandhi, the output must be MDK Gandhi. Although I get a "String index out of range" exception.

import java.util.Scanner;
public class name {

public static void main(String[] args) {
    Scanner s=new Scanner(System.in);
    System.out.println("Enter a string");
    String w=s.nextLine();
    int l=w.length();
    char ch=0; int space=0;int spacel = 0;
    for(int i=0;i<l;i++){
        ch=w.charAt(i);
        if(ch==32||ch==' '){
            space+=1;
            spacel=i+1;
            System.out.print(w.charAt(spacel) + " ");
        }            
    }
    System.out.println(w.substring(spacel,l+1));
}

Upvotes: 0

Views: 935

Answers (3)

Aryan
Aryan

Reputation: 143

import java.util.Scanner;
public class name 
{

  public static void main(String[] args) 
  {
    Scanner s=new Scanner(System.in);
    System.out.println("Enter a string");
    String w=s.nextLine();
    int l=w.length();
    char ch=0; int space=0;int spacel = 0;
    System.out.print(w.charAt(0) + " ");
    for(int i=0;i<l;i++)
    {
    ch=w.charAt(i);
    if(ch==32||ch==' ')
    {
        space+=1;

        spacel=i+1;
        System.out.print(w.charAt(spacel) + " ");

    }            
    }
    System.out.println("\b\b"+w.substring(spacel,l));
    }
    }

Upvotes: 0

Mahesh Gosemath
Mahesh Gosemath

Reputation: 426

This can be easily achieved using String's split() method or using StringTokenizer.

First split string using space as delimiter. Then according to your format last string would be Last Name and iterate over other string objects to get initial characters.

    String name = "Mohan Das Karamchand Gandhi";
    String broken[] = name.split(" ");
    int len = broken.length;
    char initials[] = new char[len-1];
    for(int i=0;i<len-1;i++) {
        initials[i] = broken[i].charAt(0);
    }
    String finalAns = new String(initials)+" "+broken[len-1];

Upvotes: 0

David Moles
David Moles

Reputation: 51093

This is the culprit:

        spacel=i+1;
        System.out.print(w.charAt(spacel) + " ");

When i is equal to l - 1, then space1 is going to be equal to l or w.length(), which is beyond the end of the string.

Upvotes: 1

Related Questions