该程序不打印谢谢(名称)。相反,该行被完全跳过,循环回到主菜单。有人可以解释一下原因吗?它应该根据指示的索引创建一个新的字符串,并将结果存储在' firstName'然后打印出来"谢谢(姓名)!"
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] custInfo = new String[20];
String MANAGERID = "ABC 132";
String userInput;
String cust = "Customer";
String pts = "Print to screen";
String exit = "Exit";
int counter = 0;
int full = 21;
boolean cont = true;
while(cont) {
System.out.println("Enter the word \"Customer\" if you are a customer or your ID if you are a manager.");
userInput = in.nextLine();
if (userInput.equalsIgnoreCase(exit)) {
System.out.println("Bye!");
System.exit(0);
}
try {
if (userInput.equalsIgnoreCase(cust)) {
System.out.println("Hello, please enter your name and DoB in name MM/DD/YYYY format.");
custInfo[counter] = in.nextLine();
String firstName=custInfo[counter].substring(0,(' '));
System.out.println("Thanks "+firstName+"!");
counter++;
}
if (counter==full) {
System.out.println("Sorry, no more customers.");
}
} catch(IndexOutOfBoundsException e) {
}
}
}
答案 0 :(得分:4)
您的代码在下面的行中生成IndexOutOfBoundsException
并跳转到异常处理程序代码。
String firstName=custInfo[counter].substring(0,(' '));
String.substring
超载,有两个定义:
substring(int startIndex)
substring(int startIndex, int endIndex)
在Java中,char
数据类型在幕后只是一个16位数。它正在将' '
(空格)转换为32,并且会在任何比此更短的String上出错(假设计数器指向有效索引)
答案 1 :(得分:1)
使用此代替custInfo[counter].indexOf(" ")
来获取name和DoB之间的空格索引:
String firstName = custInfo[counter].substring(0, custInfo[counter].indexOf(" "));