简体   繁体   中英

Java: Add to array by JOptionPane

I have this array:

String[] countriesList = {
                "Japan",
                "Sverige",
                "Tyskland",
                "Spanien",
                "Syrien",
                "Litauen",                                      
};

I want to be able to add another thing to the array, in this case this [6]th position. Is it possible to do this by JOPtionPane? This is what I've done this far, however nothing happens nor does any errors occur.

String addland = JOptionPane.showInputDialog("Vilket land vill du lägga till?").trim();
            countriesList[6] = addland;             

Arrays start their counting from 0, so you could use countriesList[5] = addland;

You may use a dynamic list to perform your task. They are better in every situation and should be superior to simple Arrays

Try to use this

List<String> countriesList = new ArrayList<>(
Arrays.asList("Japan", "Sverige", "Tyskland", "Spanien", "Syrien", "Litauen"));

String addland = JOptionPane.showInputDialog("Vilket land vill du lägga till?").trim();
countriesList.set(5,addland);
System.out.println(countriesList);

Output, after entering asdadsad :

[Japan, Sverige, Tyskland, Spanien, Syrien, asdadsad]

To add a land to the existing list use countriesList.add(addland); instead of countriesList.set(5,addland);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM