2013-09-24 29 views
0

我的程序應該打印出姓名的縮寫並打印姓氏。例如,如果輸入的名字是Mohan Das Karamchand Gandhi,則輸出必須是MDK Gandhi。雖然我得到「字符串索引超出範圍」異常。涉及子字符串()和charAt()方法的Java程序

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)); 
} 
+0

請再次閱讀' – SJuan76

+0

任何理由你不使用'lastIndexOf'爲'String.substring文檔(INT,INT)? –

+0

哪個是當前輸出? – ssantos

回答

1

這是罪魁禍首:

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

i時等於l - 1,然後space1將是等於或lw.length(),這超出了字符串的結尾。

0

這可以使用String的split()方法或使用StringTokenizer來輕鬆實現。

首先拆分字符串,使用空格作爲分隔符。然後根據你的格式,最後一個字符串將是Last Name,並迭代其他字符串對象以獲得初始字符。

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]; 
0
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)); 
    } 
    }