[英]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. 如果输入的名称是Mohan Das Karamchand Gandhi,则输出必须是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));
}
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. 当i
等于l - 1
, space1
将等于l
或w.length()
,该值超出字符串的末尾。
This can be easily achieved using String's split() method or using StringTokenizer. 使用String的split()方法或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];
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.