虽然使用hasNext方法作为条件的循环不断抛出ArrayOutOfBounds Exception? (JAVA)

时间:2012-12-06 04:46:53

标签: java arrays file bounds out

我正在使用GUI进行用户名/密码登录。我正在使用带有文件名扩展名为hasNext()的while循环作为将文件中的信息存储到数组中的条件,以便我可以将用户的输入与存储在文件中的信息进行比较。然后我使用if语句进行比较。如果匹配,则程序将用户重定向到另一个类或方法,否则它不会执行任何操作。

问题是我一直在抛出一个ArrayOutOfBounds异常,因为它试图从文件中读取第一个行。

我扔了一个System.out.println(userLogin [i])来查看它是否一直循环,但它一定不能,因为该行永远不会输出。我的猜测是,一旦进入while循环,它就会停止。我该如何解决?非常感谢您的帮助。如果您需要我澄清问题,请在评论中说明,我会重新编辑我的帖子,以尽可能清楚。这是我的代码如下:

    private class ButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e){
        String usernameInput = "";
        char passwordInput[] = {};

        if(e.getSource() == okButton){
            usernameInput = usernameTF.getText();
            passwordInput = passwordTF.getPassword();
            try{
                verifyLogin(usernameInput, passwordInput); //sends input to be verified
            }catch (IOException ed){
                JOptionPane.showMessageDialog(null, "There was a problem " +
                        "retrieving the data.");
            }
        }else if (e.getSource() == cancelButton){
            setVisible(false);
            dispose();
        }
    }

}

这是应该通过用户输入的用户名和密码发送到检查是否与文件中存储的内容匹配的方法的类和方法。

这是验证输入是否匹配的方法:

public void verifyLogin(String username, char[] password) throws IOException {
    File myFile = new File("Accounts.txt");
    Scanner inputFile = new Scanner(myFile);

        while (inputFile.hasNext()) {
            int i = 0;

            this.userLogin[i] = inputFile.next();
            System.out.println(userLogin[i]);  //says this is where the OutOfBounds occurs
            this.passLogin[i] = inputFile.nextLine();
            this.passwordCheckLogin = this.passLogin[i].toCharArray();

            if((this.userLogin[i] == username) && (this.passwordCheckLogin == password)){
                JOptionPane.showMessageDialog(null, "Access Granted");
                inputFile.close();
                break;
            }

            i++;

        }


}

文件中的信息以这种方式写入(左侧是用户名,右侧是密码):

John001 bananas
Mike001 123chocolate

谢谢!

这是整个代码,抱歉不提前包含它。希望这有助于你们更好地理解我的问题。再次感谢您抽出宝贵时间回答。

import java.util.Scanner;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;


public class DeskLogin extends JFrame {

private final int WINDOW_WIDTH = 200;
private final int WINDOW_HEIGHT = 300;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JButton okButton;
private JButton cancelButton;
private JTextField usernameTF;
private JPasswordField passwordTF;
private JPanel loginPanel;
private String userLogin[] = {};
private String passLogin[] = {};
private char passwordCheckLogin[] = {};



public DeskLogin(){
super("Login");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
buildPanel();
add(loginPanel);

}

private void buildPanel() {
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
usernameTF = new JTextField(10);
passwordTF = new JPasswordField(10);
okButton = new JButton("OK");
cancelButton = new JButton("Cancel");

loginPanel = new JPanel();

loginPanel.add(usernameLabel);
loginPanel.add(usernameTF);
loginPanel.add(passwordLabel);
loginPanel.add(passwordTF);
loginPanel.add(okButton);
loginPanel.add(cancelButton);


okButton.addActionListener(new ButtonListener());
cancelButton.addActionListener(new ButtonListener());
}

public void verifyLogin(String username, char[] password) throws IOException {
File myFile = new File("Accounts.txt");
Scanner inputFile = new Scanner(myFile);

inputFile.useDelimiter(" ");

    while (inputFile.hasNext()) {
        int i = 0;

        this.userLogin[i] = inputFile.next();
        System.out.println(userLogin[i]);
        this.passLogin[i] = inputFile.nextLine();
        this.passwordCheckLogin = this.passLogin[i].toCharArray();

        if((this.userLogin[i] == username) && (this.passwordCheckLogin == password)){
            JOptionPane.showMessageDialog(null, "Access Granted");
            inputFile.close();
            break;
        }

        i++;

    }


}

private class ButtonListener implements ActionListener {

public void actionPerformed(ActionEvent e){
    String usernameInput = "";
    char passwordInput[] = {};

    if(e.getSource() == okButton){
        usernameInput = usernameTF.getText();
        passwordInput = passwordTF.getPassword();
        try{
            verifyLogin(usernameInput, passwordInput);
        }catch (IOException ed){
            JOptionPane.showMessageDialog(null, "There was a problem " +
                    "retrieving the data.");
        }
    }else if (e.getSource() == cancelButton){
        setVisible(false);
        dispose();
    }
}

}








}

4 个答案:

答案 0 :(得分:0)

您尝试更改行以阅读System.out.println(this.userLogin[i]);怎么样?我的猜测是你有两个名为userLogin的变量,其中一个是本函数的本地变量(另一个是实例变量)。 this.userLoginuserLogin不同。道歉,如果我不在。没有违法行为。

答案 1 :(得分:0)

据我所知,将userLogin设置为零长度数组并且永远不会增加它:

private String userLogin[] = {};

因此,访问userLogin的任何元素都应该抛出异常。它与inputFile.next()调用没有任何关系。你可以做一个孤立的userLogin[0] = null,它应该会爆炸。

我建议你使用一个ArrayList或其他动态大小的结构,你可以逐步建立。

答案 2 :(得分:0)

您将这3个设置作为数组,但您从不将它们用作数组,也不会在verifyLogin之外使用它们。

private String userLogin[] = {};
private String passLogin[] = {};
private char passwordCheckLogin[] = {};

这需要额外的代码,但应该让你朝着正确的方向前进 我为那些3创建了局部变量,并调整了代码以使用它们。

public void verifyLogin(String username, char[] password) throws IOException {
    File myFile = new File("Accounts.txt");
    Scanner inputFile = new Scanner(myFile);
    String userLogin = null;
    String passLogin = null;
    char[] passwordCheckLogin = null;

    while (inputFile.hasNext()) {
        userLogin = inputFile.next();
        if (inputFile.hasNext()){
            passLogin = inputFile.next();
            passwordCheckLogin = passLogin.toCharArray();
        }
        else {
            //Need to alert that we have an improperly formatted Accounts.txt
            break;
        }
        if((userLogin == username) && (passwordCheckLogin == password)){
            JOptionPane.showMessageDialog(null, "Access Granted");
            inputFile.close();
            break;
        }
    }
}

答案 3 :(得分:0)

首先,您不需要扫描仪。 BufferedReader更简单。您可以使用拆分来排除一行中的单词。另外,请注意流的位置靠近(在末尾)。我还使用 equals 而不是 == 重新调整了条件。最后,String.valueOf允许将char数组与String进行比较。

File myFile = new File("Accounts.txt");
BufferedReader inputFile = new BufferedReader(
       new InputStreamReader(new FileInputStream(myFile)));

String line;
while ((line = inputFile.readLine())!=null) {
    int i = 0;

    this.userLogin[i] = line.split(" ")[0];
    System.out.println(userLogin[i]);
    this.passLogin[i] = line.split(" ")[1];
    this.passwordCheckLogin = this.passLogin[i].toCharArray();

    if (this.userLogin[i].equals(username) 
      && String.valueOf(this.passwordCheckLogin).equals(password)){
        JOptionPane.showMessageDialog(null, "Access Granted");                
        break;
    }

    i++;    
}
inputFile.close();