java - String 类型的方法 "nextLine()"未定义

标签 java

我正在使用多种不同的方法制作一个程序,其中之一是:

private static void IsWordPattern(String input) {

    String pattern = "";
    System.out.println("Enter a pattern of letters: ");
    pattern = input.nextLine();

}

我收到错误“字符串类型的方法“nextLine()”未定义”

但是,扫描仪在我的类(class)顶部被明确定义,

public class StringValidation {

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

我能够在我的主要功能中使用扫描仪而不会出现错误:

public static void main(String[] args) {

    Scanner input= new Scanner(System.in);

    System.out.println("Enter a string: ");
    String userInput = input.nextLine();

我还可以在另一个私有(private)且静态的方法中使用它:

私有(private)静态 int 菜单(int 选择){

    Scanner input= new Scanner(System.in);

    while(choice < 1 || choice > 9) {

        System.out.println("Select an option from the menu below: "
                + "\n1. Letters only"
                + "\n2. Numbers only"
                + "\n3. Binary data"
                + "\n4. Hexadecimal data"
                + "\n5. Binary data which represents an even number"
                + "\n6. A binary string which contains one of 2 patterns"
                + "\n7. Validate a binary stirng which contains both of the patterns"
                + "\n8. Determine if a word is a pattern"
                + "\n9. Exit");


        if(choice < 1 || choice > 9) {
            System.out.println("Invalid input -- try again\n");
        }

    }
    return choice;
}

我尝试了多种方法来修复此错误,包括将菜单函数定义更改为“private static void Menu”,但这也不起作用。为什么我会收到此错误,我该如何解决此问题。感谢任何和所有反馈。

最佳答案

您的方法参数正在隐藏同名的类字段。您可以更改参数名称或使用 this. 调用类字段,例如

 pattern = this.input.nextLine();

注意:要访问静态类变量,您可以使用类名而不是 this 关键字,在本例中它将是 StringValidation.input.nextLine()

关于java - String 类型的方法 "nextLine()"未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399182/

相关文章:

java - Java中 "if"条件的奇怪优化

java - 如何减慢 API 请求速度?

java - 如何在gui类java中显示另一个类?

java - 在启动时将位置发送到 Google 表单(如何在启动时运行 MainActivity)

java - Java新手,找不到符号报错

java - 无法通过 Eclipse Kepler 启动 Tomcat 7

java - 无法将 JDA 导入 Maven - IntelliJ IDEA

java - 在 JavaFX BubbleChart 的气泡内创建文本

java - 为什么ArrayList元素不能转换为int?

Java仪表板登录错误