对于我的计算机科学课,我正在制作一个网站用户名/密码程序。我决定使用2D字符串数组,它还没有发挥出最佳效果。我试图让文件阅读器读取写入的登录但我不断收到ArrayIndexOutOfBoundsException错误。我的文件阅读器代码如下,还包括我的登录输入代码。我刚刚开始Java,所以我有非常基本的编程知识。
private void fileReader() throws FileNotFoundException {
File inFile = new File(filePath);
try {
Scanner freader = new Scanner(inFile);
while (freader.hasNextLine()) {
for (int j = 1; j <= pass.length; j++) {
pass[j][0] = freader.nextLine();
pass[j][1] = freader.nextLine();
pass[j][2] = freader.nextLine();
}
}
freader.close();
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
登录输入:
private void input() throws InterruptedException, FileNotFoundException {
for (int i = 0; i < pass.length; i ++){
System.out.println(i);
if (i == pass.length){
add();
}
c.print("Please enter the website: ");
pass[i][0] = c.readLine();
c.print("Please enter your username: ");
pass[i][1] = c.readLine();
c.print("Please enter your password: ");
pass[i][2] = c.readLine();
while (true){
c.clear();
synchronized (c) {
c.println("To continue adding logins, press C. To exit the program press ESC.");
c.println(pass[i][0] + " " + pass[i][1] + " " + pass[i][2]);
}
if (c.isKeyDown(KeyEvent.VK_C)){
break;
}
else if (c.isKeyDown(KeyEvent.VK_ESCAPE)){
fileWriter();
pass();
}
Thread.sleep(10);
}
}
}
非常感谢任何帮助!!谢谢!
答案 0 :(得分:1)
主要原因是因为:
for (int j = 1; j <= pass.length; j++) {
pass[j][0] = freader.nextLine();
pass[j][1] = freader.nextLine();
pass[j][2] = freader.nextLine();
}
数组从0开始。通过使j = 1,您从组中的第二个数组开始,您需要从0开始并读取但不包括数组长度。