使用JOptionPane填充数组

时间:2015-01-31 18:59:47

标签: java arrays

程序要求学生数量,然后询问名称并将其保存在数组中并打印所有这些名称。 我无法保存所有名称,程序只打印最后一个或在for循环中崩溃。可能是什么问题?

package tarea3_1;

import javax.swing.*;

public class Tarea3_1 {

    public static void main(String[] args) {

        int Num, f;
        String[] NumArray;

        Num = Integer.parseInt(JOptionPane.showInputDialog(null,
                "Ingrese numero de estudiantes: "));
        NumArray = new String[Num];

        for (f = 1; f <= NumArray.length; f++) {

            String[] Stu;
            Stu = new String[f];
            Stu[f] = JOptionPane.showInputDialog("Nombre " + f + ": ");

            for (int R = 0; R < Num; R++) {
                JOptionPane.showMessageDialog(null, Stu[R]);
            }

        }

    }

}

2 个答案:

答案 0 :(得分:0)

怎么样:

import java.util.TreeMap;
import javax.swing.*;

public class Tarea3_1 {

    public static void main(String[] args) {

        int nbStudents;
        TreeMap<Integer, String> students = new TreeMap<>();
        try {
            nbStudents = Integer.parseInt(JOptionPane.showInputDialog("Number of students:"));
        } catch (NumberFormatException ex) {
            nbStudents = Integer.parseInt(JOptionPane.showInputDialog("Number of students:"));
        }

        for (int i = 0; i < nbStudents; i++) {
            String name = JOptionPane.showInputDialog("Student " +  i);
            students.put(i, name);
        }

        System.out.println(students);
    }

}

答案 1 :(得分:0)

我不太了解您尝试做什么,但我希望此代码可以帮助您

package tarea3_1;

import javax.swing.*;

public class Tarea3_1 {

public static void main(String[] args) {

    int Num, f;
    String[] NumArray;

    Num = Integer.parseInt(JOptionPane.showInputDialog(null,
            "Increse numero des etudiants: "));
    NumArray = new String[Num];

    for (f = 0; f < NumArray.length; f++) {

        NumArray[f] = JOptionPane.showInputDialog("Nombre " + f + ": ");
    }

    for (int R = 0; R < NumArray.length; R++) {
        names += NumArray[R] +"\n";

    }
    JOptionPane.showMessageDialog(null, names );
}

}