2015-01-31 184 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); 
    } 

}