0

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

Jongware
  • 21,058
  • 8
  • 43
  • 86
noBrainer
  • 29
  • 1
  • 4

3 Answers3

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
msfoster
  • 2,231
  • 1
  • 14
  • 18
1

solution is very simple

String[] userInfo = new String[4];
aarr
  • 21
  • 2
0

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....

Hitesh Garg
  • 1,071
  • 1
  • 9
  • 20
  • U r Welcome @noBrainer. If this really helps you then don't forget to plus one and Accept the Answer as it will help future visitors of this post. – Hitesh Garg Sep 26 '14 at 12:29