简体   繁体   English

Java JOptionPane:如何在字符串中获取用户输入并将其存储在数组中?

[英]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.我还尝试采用不同数据类型(例如 int 和 String)的多个输入并使它们相互对应。 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);如果你想要整数(因为 JOptionPane.showInputDialog 将返回一个字符串),你可以做的是使用Integer.parseInt(jobName); where jobName is the user input.其中jobName是用户输入。

This code will store all values from String[] into int[] , you can place it after the first code sample:此代码会将String[] 中的所有值存储到int[] 中,您可以将其放在第一个代码示例之后:

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:要将薪水“链接”jobName,您只需确保这些值位于同一索引中,而不是获取工作名称和薪水,您可以这样做:

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


Best regards, Brhaka最好的问候, 布拉卡

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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