我之前的问题已经结束,但是建议的答案对我没有太大帮助。不便之处,敬请原谅。
我正在尝试将fname
,lname
,address
,city
,state
和zip
存储在数组customerData[30][6]
中。但是,似乎在我输入信息的地方跳过了行。
代码
public void addCustomer() throws IOException {
Scanner scan = new Scanner(System.in);
int numCustomers = 0;
String[][] customerData = new String[30][7];
System.out.println("how many customers");
numCustomers = scan.nextInt();
BufferedWriter writer = new BufferedWriter(
new FileWriter("/Users/simonshamoon/eclipse-workspace/Final Project/src/customerdata.txt"));
BufferedWriter loginWriter = new BufferedWriter(
new FileWriter("/Users/simonshamoon/eclipse-workspace/Final Project/src/userlogin.txt"));
for (int i = 0; i < numCustomers; i++) {
System.out.println("enter customer data (fname, lname, address, city, state, zip)");
for (int j = 0; j < customerData[i].length; j++) {
customerData[i][j] = scan.nextLine();
}
writer.write(customerData[i][0] + ", " + customerData[i][1] + ", " + customerData[i][2] + ", "
+ customerData[i][3] + ", " + customerData[i][4] + ", " + customerData[i][5] + "\n");
loginWriter.write(customerData[i][0].charAt(0) + customerData[i][1] + ", " + rand.nextInt(10001) + "ASU"
+ ", Customer" + "\n");
}
writer.flush();
writer.close();
loginWriter.flush();
loginWriter.close();
}
输出
how many customers
1
enter customer data (fname, lname, address, city, state, zip)
fname
lname
123 address dr
city
state
zip
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at Employee.addCustomer(Employee.java:156)
at Employee.displayEmployeeMenu(Employee.java:196)
at BasicMethods.promptUser(BasicMethods.java:48)
at Shop.main(Shop.java:8)
我想要它以便customerData[i][0] = fname
,customerData[i][1] = lname
等。我尝试使用.nextLine
和数组大小,但是我认为问题出在address
中所需的空间。
因此您在这里创建客户数据:
for (int j = 0; j < customerData[i].length; j++) {
customerData[i][j] = scan.nextLine();
}
这是使用charAt
的编写者代码:
loginWriter.write(customerData[i][0].charAt(0) + customerData[i][1] + ", " + rand.nextInt(10001) + "ASU" + ", Customer" + "\n");
所以看起来customerData[i][0]
是一个空字符串,因为它是charAt
的唯一使用,它会引发索引异常。
我建议您要么输出单个数据项,要么更好,使用调试器逐步执行代码。
由于您没有显示周围的代码(scan
是如何创建的;也许它被重用,但同时又意外关闭了?),我们只能做出合理的猜测。