如何从静态上下文引用非静态变量名? [英] How to reference non-static variable name from static context?

查看:148
本文介绍了如何从静态上下文引用非静态变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个允许用户输入团队名称的代码。
这是我的代码:

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)如何在不静止的情况下引用它?

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

b)有没有办法让用户输入并直接将其分配给变量name,即没有:

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

推荐答案

static 方法不允许直接使用非静态变量,因为非静态/实例变量在对象创建时在内存中初始化。因此,您需要创建该类的对象,然后使用该变量。做这样的事情:

static methods do not allow to use the non-static variables directly because non-static/instance variables are initialized in memory on object creation. Hence you need to create an object of the the class and then use the variable. Do something like this:

Team teamObj = new Team();
//now access name variable using teabObj instance
teamObj.name = tn.nextLine();    

这篇关于如何从静态上下文引用非静态变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆