当前停留在一项要求我打印用户名的作业上,例如:Last,First Initial。 (Bob,BillyH。)如果在输入时在名字和中间名之间添加太多空格,则会获得索引超出范围的异常。 (字符串超出范围0)除非我的名字和中间名之间有多个空格,否则程序将完全正常运行。
我只能在该程序中使用trim,indexOf,substring和charAt方法。
import java.util.Scanner;
public class Name {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
int secondSpace = name.indexOf(" ", (firstSpace + 1));
middle = name.substring((firstSpace + 1), secondSpace);
middle.trim();
last = name.substring(secondSpace+1);
char middleInitial = middle.charAt(0);
String initial = "";
initial = initial + middleInitial;
for(int i = 1; i < middle.length(); i++) {
char currentLetter = middle.charAt(i);
char lastLetter = middle.charAt(i - 1);
if(lastLetter == ' ') {
initial = initial + "." + currentLetter;
}
}
System.out.println(last + "," + first + ' ' + initial + ".");
}
}
答案 0 :(得分:0)
输入错误的原因
amid skum asdf
以上输入:
int firstSpace = name.indexOf(' '); //firstSpace = 0
int secondSpace = name.indexOf(" ", (firstSpace + 1));//secondSpace = 1
middle = name.substring((firstSpace + 1), secondSpace); // as the two or more continues space inputted, this will select empty string as firstSpace + 1 == secondSpace and later causing the exception
执行name = name.replaceAll(" +", " ");
来替换所有两个或更多的空格。
正如karthik在评论中建议的那样,执行作业middle = middle.trim();
。
编辑:
由于无法使用replaceAll
,因此仅使用trim
方法即可修改代码。请仔细阅读以下片段:
String middleNameLastName = name.substring(firstSpace+1).trim();
last = middleNameLastName.substring(index+1).trim();
这些将删除尾随空格。
import java.util.Scanner;
public class Post1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
String middleNameLastName = name.substring(firstSpace+1).trim();
int index = middleNameLastName.indexOf(" ");
middle = middleNameLastName.substring(0, index);
last = middleNameLastName.substring(index+1).trim();
System.out.println(last + "," + first + ' ' + middle.charAt(0) + ".");
s.close();
}
}