0

该代码假设打印用户输入的名称,但它只是打印空值而不是打印实际名称。我正在使用数组来存储名称值。

import javax.swing.JOptionPane;

class PrintName {
    public static void main(String[] args) {

         int nameCount = Integer.parseInt(JOptionPane.showInputDialog(null, " how many NAMES you want to enter?"));
         String [] userFirstName = new String [nameCount];
         String [] userLastName = new String [nameCount];
         for (int i=0; i<nameCount; i++) {
             fullName(userFirstName[i], userLastName[i]);
         }

         for (int i=0; i<nameCount; i++) {
         JOptionPane.showMessageDialog(null, userFirstName[i] + "\n" + userLastName[i]);
    }

    public static void fullName (String firstName, String nLastName) {
        firstName = JOptionPane.showInputDialog(null, "What's your first name?");
        nLastName = JOptionPane.showInputDialog(null, "What's your last name?");
    }

}
4

2 回答 2

2

那是因为您输入和获取的名称fullName()并未反映在实际数组userFirstName中,userLastName.

原因是,它是一个pass by value. 您将userFirstName[i]每次(实际上是null)的副本传递给您的fullName()方法,并在那里修改本地副本。firstName对阵列所做的更改nLastName不会反映回您的userFirstName阵列。

你可以做的一件事来解决它。

for (int i = 0; i < nameCount; i++) {
    userFirstName[i] = JOptionPane
                    .showInputDialog(null, "What's your first name?");
    userLastName[i] = JOptionPane.showInputDialog(null, "What's your last name?");
}

在循环中获取main()方法中的值。for

于 2013-03-30T04:57:24.237 回答
2

I think that happen because you change the value and not the value pointer, change the firm of fullName for this:

public static void fullName (String[] firstName, String[] nLastName, int i) {
    firstName[i] = JOptionPane.showInputDialog("What's your first name?");
    nLastName[i] = JOptionPane.showInputDialog("What's your last name?");
}

And now you can call the function with this way:

fullName(userFirstName, userLastName, i);

I hope this works for you :)

于 2013-03-30T05:05:33.720 回答