如何使用方法调用为数组赋值

时间:2013-07-07 07:32:47

标签: java

我一直试图弄清楚如何为数组赋值。

stringName数组的大小是通过用户输入(getNumberofStrings方法)确定的。我希望用户通过JOptionPane输入stringName数组的值。我编写了一个方法(getStringName),但无法弄清楚如何从main方法调用它。对这位初学者的任何建议都非常感谢。

public class NoClassp3 {

public static void main(String[] args) {
    int numberOfStrings = getNumberOfStrings();
    String[] stringName = new String[numberOfStrings];
}   // end method main

public static int getNumberOfStrings() {
   String input = JOptionPane.showInputDialog("Enter number of strings in integer format");
   int number = Integer.parseInt(input);
   return number;
}   // end method getNumberOfStrings

public static String getStringName(String[] name) {
    String input = JOptionPane.showInputDialog("Enter string name");
    for (int i = 0; i < name.length; i++)
        name[i] = input;
    return input;
}   // end method getStringName
}   // end class NoClassp3

1 个答案:

答案 0 :(得分:0)

试试这个

public class NoClassp3 {

public static void main(String[] args) {
    int numberOfStrings = getNumberOfStrings();
    String[] stringName = new String[numberOfStrings];
    stringName = getStringName(stringName);

    for (int i = 0; i < stringName.length; i++)
    {
        System.out.println(stringName[i]);
    }
}   // end method main

public static int getNumberOfStrings() {
   String input = JOptionPane.showInputDialog("Enter number of strings in integer format");
   int number = Integer.parseInt(input);
   return number;
}   // end method getNumberOfStrings

public static String[] getStringName(String[] name) {
    for (int i = 0; i < name.length; i++)
        name[i] = JOptionPane.showInputDialog("Enter string name");
    return name;
}   // end method getStringName
}   // end class NoClassp3