This question already has an answer here:
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
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
solution is very simple
String[] userInfo = new String[4];
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