0

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?

1
  • What is name in System.out.println("Welcome " + name);? Read up on variable scope. Commented Apr 13, 2014 at 23:14

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Or System.out.println("Welcome " + name());
@codeNinja It would help for the OP to learn variable assignments. One is not going to nest function calls in arguments for an entire program.
It's just another option. But right, you still shouldn't because it is good to have a variable to modify later on.
1

Your name() method is static, but that doesn't necessarily mean that the namevariable 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.