【问题标题】:The method "nextLine()" is undefined for the type String未为 String 类型定义方法“nextLine()”
【发布时间】:2019-10-15 16:38:07
【问题描述】:

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

private static void IsWordPattern(String input) {

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

}

我收到错误,“方法“nextLine()”未定义为 String 类型”

但是,扫描仪在我班上是明确定义的,

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();

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

私有静态整数菜单(整数选择){

    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;
}

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

【问题讨论】:

  • 您正在重用变量名input。所以IsWordPattern 方法看不到Scanner 变量,它只能看到String 变量。没有nextLine 方法。只需更改 String 输入参数的名称即可。

标签: java


【解决方案1】:

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

 pattern = this.input.nextLine();

注意:要访问静态类变量,您将使用类名而不是 this 关键字,在这种情况下,它将是 StringValidation.input.nextLine()

【讨论】:

  • 注意:变量是静态的
  • @cricket_007 注意到
【解决方案2】:

类中的扫描仪变量被名为input 的字符串参数所遮蔽。您应该重命名函数参数,然后扫描仪再次可见。

【讨论】:

    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    相关资源
    最近更新 更多