Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference non-static variable name from static context?

Tags:

java

I am trying to write a code that lets the user enter a team name. Here is my code:

public class Team {
    public String name;

    public static void main(String[] args) {
        System.out.println("Enter name team");
        Scanner tn = new Scanner(System.in);
        name = tn.nextLine();     
    }
}

I understand that "non-static variable name cannot be referenced from a static context". I know that if I take the "static" away from the main then it will work, but:

a) How can I reference it without taking the "static" out?

b) Is there a way to get the users input and assign it straight to the variable "name" i.e. without the:

Scanner tn = new Scanner(System.in);
name = tn.nextLine(); 

Basic questions I know, but I am still a beginner! Many thanks, Miles

like image 233
Miles Roberts Avatar asked Mar 04 '26 03:03

Miles Roberts


1 Answers

name is a team name. So you need to instantiate a new Team object and set its name :

public static void main(String[] args) {
    System.out.println("Enter name team");
    Scanner tn = new Scanner(System.in);
    Team team = new Team();
    team.name = tn.nextLine();     
}
like image 99
Arnaud Avatar answered Mar 05 '26 15:03

Arnaud



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!