Choco Fernandez Choco Fernandez - 4 months ago 11
Java Question

Cannot store values in the attributes

I created a class called Person. I'm having troubles storing data within the attributes of the constructor in the class. I made a tester and tried it out with the first constructor but it says it cannot find the variable. What I'm really trying to do is make an array of the Person class—the number of "Person" will depend on the input(choice) of the user—and display it.

public class Person
{
private String fname;
private String lname;
private byte age;

public Person(String fn, String ln, byte edad)
{
fname=fn;
lname=ln;
age=edad;
}
public Person(String fn, String ln)
{
fname=fn;
lname=ln;
age=20;
}
public int getAge()
{
return age;
}
public String getFname()
{
return fname;
}
public String getLname()
{
return lname;
}
}


Here is the tester code:

import java.util.Scanner;
public class TestPerson

{
public static void main(String []args)
{
Scanner scan = new Scanner(System.in);
int choice, ctr;
System.out.print("How many Person: ");
choice = scan.nextInt();
Person p1 =new Person(fname, lname, age);
Person[] Arr = new Person[choice];
for(ctr=0; ctr<choice; ctr++){
System.out.print("First name:");
fname=scan.next();
System.out.print("Last name:");
lname=scan.next();
System.out.print("Age:");
age=scan.nextInt();
}
}
}

Bon Bon
Answer

You need to declare your variables (fname, lname, age) first before they can be assigned a value or used.

The following statement declares a String variable fname and assign it the next string token in the console input.

String fname = scan.next();

Then use this variable as the constructor argument for person, like:

Person p1 = new Person(fname, lname, age);

Put it all together, it should be like:

Person[] Arr = new Person[choice];
    for(ctr=0; ctr<choice; ctr++){
        System.out.print("First name:");
        String fname = scan.next();
        System.out.print("Last name:");
        String lname = scan.next();
        System.out.print("Age:");
        byte age = scan.nextByte();

        Person p1 = new Person(fname, lname, age);
        Arr[ctr] = p1;
    }