[英]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 - 1
, space1
將等於l
或w.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.