Array “out of bounds” [duplicate]

我与影子孤独终老i 提交于 2019-11-30 09:58:39

问题


I'm using an array of String[3] to store user input which is got from 4 JTextFields I then output the array to a txt file:

String[] userInfo = new String[3];
    userInfo[0] = sourceTextField.getText();
    userInfo[1] = usernameTextField.getText();
    userInfo[2] = passwordTextField.getText();
    userInfo[3] = emailTextField.getText();
    for (String userInfo1 : userInfo) {
        try 
        {
            BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\Peace Infinity\\Desktop\\[programming]Projects\\DataFiles\\PasswordRepository.txt", true));
            String s;
            s = userInfo1;
            writer.write(s + " ");
            writer.flush();
        }catch (IOException ex) 
        {
            Logger.getLogger(ADD_dialogBox_v1.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Error processing file!");
        }
    }

Can someone tell me why I'm getting exception "array index out of bounds"? Thank you


回答1:


When you declare an array you provide the length/size of that array. An array starts at index 0 as you've done in your code, but you're trying to assign a value to an index "out of bounds" - the fourth index.

new String[3] // index 0,1,2
new String[4] // index 0,1,2,3



回答2:


solution is very simple

String[] userInfo = new String[4];



回答3:


You are using a smaller Array.... do this

String[] userInfo = new String[4];

I would suggest you to use Arraylist as this does not require any size to declare and can accomodate any number of items.

  ArrayList<String> userInfo = new ArrayList<>();
    userInfo.add(sourceTextField.getText());
    userInfo.add(usernameTextField.getText());
    userInfo.add(passwordTextField.getText());
    userInfo. dd(emailTextField.getText());
     for (String userInfo1 : userInfo) {
        try 
        {.......
           ............

And the rest of the code proccessed accordingly....



来源:https://stackoverflow.com/questions/25983096/array-out-of-bounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!