java - String 类型的方法“nextLine()”未定义
问题描述
我正在用多种不同的方法制作一个程序,其中之一是:
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();
以及我能够在另一种也是私有和静态的方法中使用它:
私人静态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()
推荐阅读
- r - `dplyr:::bind_rows_` 有什么作用?
- elixir - Elixir Phoenix Plugs 及其放置位置
- mongodb - MongoDB:对 UTF-8 字符串进行排序
- javascript - Javascript - 创建和填充包含子数组的关联数组
- json - JSON VB.Net 的类
- itext - iText PdfSmartCopy 正在创建重复字体
- elasticsearch - 无法索引/发现 Elassandra 中的多个字段
- javascript - JQuery Datatable 标头与 tbody 不对齐?
- statistics - ANOVA 结果不一致(AIC VS 偏差)
- java - Apache nifi 无法启动