-->

How do i add data from a variable to an array?

2019-08-24 01:45发布

问题:

So basically I created an array.

int[] idarray = new int [5];

Now I want the user to input something.

idd = JOptionPane.showInputDialog ("\nEnter ID number:\n\n");
id = Integer.parseInt(idd);

and whatever the data may be would go to the array idarray.

How do I add the data from the variable into the array?

回答1:

Firstly, you should be using a List<Integer> (which would allow you to accept unlimited user input), but if you must use an array, this will work to fill your array from user input:

for (int i = 0; i < idarray.length; i++) {
    idd = JOptionPane.showInputDialog ("\nEnter ID number:\n\n");
    id = Integer.parseInt(idd);
    idarray[i] = id;
}


回答2:

idarray[i] = id; // of course you have to decide i yourself

if you want to simply appending things, you could use ArrayList instead of plain array.



标签: java arrays