Reputation: 51
This is a program that asks the user to enter 1 to store name. Then the program will prompt the user to enter his/her name. After, the program stores the data in an array. Then i have to use a method to do the storage. However, I have a getter and setter methods but i get an error "error: Name has private access in className".
I would like to return the name from my "className" constructors.
I appreciate your assistance. Thanks.
Main Class "ReturnName"
import javax.swing.JOptionPane;
public class ReturnName
{
public static void main (String[] args)
{
className x = new className();
int menu = Integer.parseInt(JOptionPane.showInputDialog("Choose an option:" + "\n" +
"Enter 1 to store name"));
if(menu == 1){
String[] input1 = new String[1];
for(int i = 0; i < input1.length; i ++){
String str1 = JOptionPane.showInputDialog("Enter your name");
input1[i] = str1;
}
method(input1);
}
}public static void method(String [] input1){
String Name = "";
for(int i = 0; i < input1.length; i++){
Name = input1[i];
}
className HoldName = new className();
System.out.println(HoldName.Name);
}
}
className
class className{
private int Menu;
private String Name;
public className(){
Menu = 0;
Name = "";
}
public className(String n, int m){
Menu = m;
Name = n;
}
public String getName(){
return Name;
}
public int getMenu(){
return Menu;
}
public void setName(String n){
Name = n;
}
public void setMenu(int m){
Menu = m;
}
}
Upvotes: 0
Views: 274
Reputation: 12398
The issue is that ReturnName
attempts to read the value of the private variable Name
. Remember that a private variable is just that: private, i.e. it can only be read and written from the object where that variable is declared. If other objects want to access that variable, they must go through the getter method.
EDIT: the name is not printed because the method setName
is never called. The for loop in method
is also wrong.
Do:
public static void method(String name){
className holdName = new className();
className.set(name);
System.out.println(holdName.getName());
}
And call it as:
String str1 = JOptionPane.showInputDialog("Enter your name");
method(str1);
Upvotes: 1
Reputation: 6802
Yes because the access modifier of Name
is private and you can't access it this way, so instead of directly calling HoldName.Name
use getter method HoldName.getName()
Upvotes: 5