简体   繁体   中英

Java JOptionPane: How to take an user input in String and store it in an array?

String jobName;
jobName = JOptionPane.showInputDialog("Enter Job Name " + i);
String[] numberofjobs; 
numberofjobs = new String[jobName];

I'm trying to take an user input as a String and store into an array, what am I doing wrong here?

I'm also trying to take multiple inputs of different data types (eg int and String) and have them correspond to each other. How do I go about this?

This code works:

String[] numberofjobs = new String[10];
String jobName = JOptionPane.showInputDialog(null, "Enter Job Name " + i);

if(jobName != null) {
    numberofjobs[0] = jobName;
}

Learn more about arrayshere .

What you can do if you want ints (since JOptionPane.showInputDialog will return a String), is use Integer.parseInt(jobName); where jobName is the user input.

This code will store all values from String[] into int[] , you can place it after the first code sample:

int[] intArray = new int[numberofjobs.length];

for (int i = 0; i < numberofjobs.length; i++) {
    intArray[i] = Integer.parseInt(numberofjobs[i]);
}

To 'link' the salary to jobName you just have to be sure that the values are in the same index, than to get the job name and salary you can just do this:

String jobNameAndSalary = numberofjobs[0] + ", with the salary of " + salaries[0];


Best regards, Brhaka

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