我如何创建一个数组,我希望数组中有8个值,但用户输入它们?
这是我到目前为止所拥有的
import javax.swing.JOptionPane;
public class Southside Report {
public static void main(String[] args) {
int FINAL MIN_STAFF = 7;
int total_staff = 0;
double[] num_students = 8;
答案 0 :(得分:3)
您应将array
声明为:
double[] num_students = new double[8];
int FINAL MIN_STAFF = 7;
应为FINAL int MIN_STAFF = 7;
然后您可以通过执行以下操作JOptionPane
来分配值:
int i=0;
while(i<8){
try{
num_students[i]=Double.parseDouble(JOptionPane.showInputDialog("Enter Number:"));
i++;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Please enter valid number");
}
}
答案 1 :(得分:3)
看看JOptionPane。选项窗格非常可定制。除了你的代码没有编译我认为你希望用户只在一个对话框中输入8个文本,你可以使用optionPane进行一些自定义,如下例所示。
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JOptionPaneTest {
public static final int OPTIONS = 8;
private List<JTextField> textfields = new ArrayList<>(OPTIONS);
private JPanel panel;
public JOptionPaneTest(){
panel = new JPanel();
for(int i =0;i< OPTIONS;i++){
JTextField textfield = new JTextField(5);
textfields.add(textfield);
panel.add(new JLabel(Integer.toString(i+1)+": "));
panel.add(textfield);
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
JOptionPaneTest example = new JOptionPaneTest();
int result = JOptionPane.showConfirmDialog(null, example.panel,
"Please Enter Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
for(JTextField textfield : example.textfields){
System.out.println(textfield.getText());
}
}
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
输出: