[英]Why isn't my println working?
该程序没有打印出感谢(姓名)。 取而代之的是,该行被完全跳过,循环回到主菜单。 有人可以解释为什么吗? 它应该根据指示的索引创建一个新字符串,并将结果存储在“ 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) {
}
}
}
您的代码在下面的行上生成IndexOutOfBoundsException
,并跳转到Exception处理程序代码。
String firstName=custInfo[counter].substring(0,(' '));
String.substring
重载,并且具有两个定义:
substring(int startIndex)
substring(int startIndex, int endIndex)
在Java中, char
数据类型只是幕后的16位数字。 它将' '
(空格)转换为32,并且任何短于该字符串的String都会出错(假定计数器指向有效索引)
使用此代替custInfo[counter].indexOf(" ")
获取名称和DoB之间的空间的索引:
String firstName = custInfo[counter].substring(0, custInfo[counter].indexOf(" "));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.