如何在Java中使用扫描仪? [英] How to use scanner in java?

查看:45
本文介绍了如何在Java中使用扫描仪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.Scanner;  

public class Initials {  
    Scanner getin = new Scanner (System.in);  
    public static void main(String[] args) {  
        String Name;  
        System.out.println("Enter your name's Initials::");  
        Name=getin.nexlinet();  
    }  
}

错误:不能从静态上下文中引用非静态变量吗?

error : non-static variable cannot be referenced from a static context?

推荐答案

首先, Scanner 对象没有名为 nexlinet 的方法,我想您想要改为 nextLine().

First of all, Scanner objects doesn't hava a method called nexlinet, I guess you want nextLine() instead.

关于该错误,您不能从 static 方法引用非静态变量(在这种情况下,该方法是 main ).

About the error, you can't reference a non-static variable from a static method (in this case, that method is main).

为什么?因为即使没有创建该类的实例,也可以使用 static 变量.

Why? Because static variables can be used even if no instances of the class have been created.

如何解决?

  • 您可以将变量 getin 声明为 static :

static Scanner getin = new Scanner(System.in);

  • 或者您可以创建该类的实例并访问实例字段 getin :

    Initials some_name = new Initials();
    // ...
    name = t.getin.nextLine();
    

  • 注释:

    • 尝试遵循Java命名约定.将'mixedCase'用于方法/变量,并将'CamelCase'用于类/接口.
    • 我建议您阅读有关访问修饰符的信息.为什么?看第二种解决方法.类 Initials 应该为实例字段 getin 提供一个 getter/setter 方法,因此您没有完全的访问权限.另外,将实例字段声明为 private (并使用 getters/setters )也是一种好习惯.
    • Try to follow Java naming conventions. Use 'mixedCase' for methods/variables and use 'CamelCase' for classes/interfaces.
    • I'd recommend you to read about access modifiers. Why? Look at the second solving way. The class Initials should provide a getter/setter method for the instance field getin, so you don't have full access on it. Also, it's a good practice to declare instance fields as private (and use getters/setters).

    这篇关于如何在Java中使用扫描仪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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