user2178940
user2178940

Reputation: 15

Code outputs NULL instead of value

The code suppose to print names entered by user but it is just printing the null values instead of printing actual names. I am using array to store the names values.

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

}

Upvotes: 0

Views: 123

Answers (2)

tonylattke
tonylattke

Reputation: 98

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 :)

Upvotes: 2

Rahul
Rahul

Reputation: 45060

That's because the names you entered and fetched in your fullName() are not reflected in the actual arrays userFirstName, userLastName.

The reason being, its a pass by value. You are passing a copy of your userFirstName[i] everytime(which is actually null), to your fullName() method, and modifying the local copy there. The changes made to firstName and nLastName won't be reflected back to your userFirstName array.

One thing you could do to fix it is this.

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

Getting the values in the main() method, within the for loop.

Upvotes: 2

Related Questions