程序没有打印出感谢(名字)。相反,该行被完全跳过,循环回到主菜单。有人能解释一下为什么吗?它应该根据指定的索引创建一个新字符串,并将结果存储在'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) {
}
}
}发布于 2017-02-22 05:22:24
您的代码将在下面的行上生成一个IndexOutOfBoundsException,并跳转到异常处理程序代码。
String firstName=custInfo[counter].substring(0,(' '));String.substring是重载的,它有两个定义:
substring(int startIndex)
substring(int startIndex, int endIndex)在Java语言中,char数据类型只是幕后的16位数字。它正在将' ' (空格)转换为32,并且将在任何长度小于32的字符串上出错(假定计数器指向有效的索引)
发布于 2017-02-22 05:24:54
使用下面的代码来获取name和DoB之间空格的索引:
String firstName = custInfo[counter].substring(0, custInfo[counter].indexOf(" "));https://stackoverflow.com/questions/42378086
复制相似问题