该程序没有打印出感谢(名称)。取而代之的是,该行被完全跳过,回到主菜单。有人可以解释为什么吗?它应该根据指示的索引创建一个新字符串,并将结果存储在" firstName"中,然后将其打印为" thess(name)!"
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) {
}
}
}
您的代码在下面的行上生成IndexOutOfBoundsException
,然后跳到异常处理程序代码。
String firstName=custInfo[counter].substring(0,(' '));
String.substring
已重载,有两个定义:
substring(int startIndex)
substring(int startIndex, int endIndex)
在Java中,char
数据类型只是幕后16位数字。它正在将' '
(空间)转换为32,并且在任何短的字符串上都将错误(假定计数器指向有效索引)
使用此代替 custInfo[counter].indexOf(" ")
获取名称和dob之间的空间索引:
String firstName = custInfo[counter].substring(0, custInfo[counter].indexOf(" "));