2015-01-31 120 views
0

程序会询问学生人数,然后查找姓名并将其保存在数组中并打印所有人。 我无法保存所有名称,程序只打印最后一个或在for循环中崩溃。可能是什么问题呢?使用JOptionPane填充数组

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]); 
      } 

     } 

    } 

} 

回答

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); 
} 

} 
+0

感谢你使它看起来那么容易 – Raptor26 2015-01-31 19:59:55

+0

现在的输出必须是所有的学生在一个JOptionPane框 – Raptor26 2015-01-31 20:08:52

+0

@ Raptor26:请编辑代码可以帮助你 – esprittn 2015-01-31 20:25:24

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); 
    } 

}