Reputation: 305
Creating a text based game. I have a method for each of the following: Race, profession, name. So for instance:
public static void main(String[] args) {
// TODO code application logic here
intro();
name();
System.out.println("Welcome " + name);
}
public static String name(){
System.out.println("Enter Name:");
String name = sc.next();
return name;
}
Yet I get an error when using the name variable in my print in main. Why?
Upvotes: 0
Views: 50
Reputation: 79
Your name()
method is static, but that doesn't necessarily mean that the name
variable in that method can be accessed without a getter
or something similar. It won't recognize that variable since it's only defined in that method.
You can try something like Sysout("welcome" + name());
since your method will return that value.
Upvotes: 1
Reputation: 41311
You need to assign the return value of name
to a local variable:
public static void main(String[] args) {
// TODO code application logic here
intro();
String name = name();
System.out.println("Welcome " + name);
}
public static String name(){
System.out.println("Enter Name:");
String name = sc.next();
return name;
}
Upvotes: 4