Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing user input string from another class?

Tags:

java

I'm trying to write a program that asks the user for input using the scanner class to name something. Then in a completely different class, reference that input.

For example:

class TeamInfo {
    Scanner nScan = new Scanner(System.in);

public String GetName(){
    String GetName = nScan.nextLine();

}

The issue I'm having is that the first time I reference the GetName method in the TeamInfo class, it works--At the right spot, it prompts for the team name.

However, it prompts for the team name every time after that. I can't seem to find anywhere online or in my Java Beginner's Guide how to make this input constant, so that I can reference the input. I'm also not entirely sure what it is I'm looking for, so that doesn't help.

In other words, what I want is to prompt the user one time, and then remember that answer and re-use it again and again.

like image 707
C-Love511 Avatar asked Jan 21 '26 09:01

C-Love511


1 Answers

You should make two methods: getName() and promptName() (or whatever names you like best)

One method would be for retrieving the name from the user, and the other would be for retrieving the value that you got from the user:

class TeamInfo {
    private Scanner nScan = new Scanner(System.in);
    private String name;

    public void promptName() {
        name = nScan.nextLine();
    }

    public String getName() {
        return name;
    }
}

When you want to get the name from the user, you'd call:

TeamInfo info = new TeamInfo();
info.promptName();

And when you wanted to retrieve the name for your uses:

String teamName = info.getName();
like image 147
crush Avatar answered Jan 24 '26 01:01

crush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!