loops - Java program involving substring() and charAt() methods -


my program supposed print out initials of name , print last name. eg. if name entered mohan das karamchand gandhi, output must mdk gandhi. although "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 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)); } 

this culprit:

        spacel=i+1;         system.out.print(w.charat(spacel) + " "); 

when i equal l - 1, space1 going equal l or w.length(), beyond end of string.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -