簡體   English   中英

涉及substring()和charAt()方法的Java程序

[英]Java program involving substring() and charAt() methods

我的程序應該打印出名稱的首字母並打印姓氏。 例如。 如果輸入的名稱是Mohan Das Karamchand Gandhi,則輸出必須是MDK Gandhi。 雖然我得到“字符串索引超出范圍”異常。

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

這是罪魁禍首:

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

i等於l - 1space1將等於lw.length() ,該值超出字符串的末尾。

使用String的split()方法或StringTokenizer可以輕松實現這一點。

首先使用空格作為分隔符分割字符串。 然后根據您的格式,最后一個字符串將是“姓氏”,並遍歷其他字符串對象以獲取初始字符。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM