JAVA中“Cannot make a static reference to the non-static method nextLine() from the type Scanner”的解決方法
阿新 • • 發佈:2021-01-06
一個簡單的從控制檯接收輸入的身份證號,按照所給程式碼打出
public class InputCode {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //建立輸入流掃描器
System.out.println("請輸入你的身份證號碼");
String line = Scanner.nextLine();
System.out.print("原來你的身份證號碼是" + line.length() + "位數字啊");
}
}
執行起來總會報錯
無法從型別掃描程式對非靜態方法nextLine()進行靜態引用
當將程式碼改成下列時
public class InputCode {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //建立輸入流掃描器
System.out.println("請輸入你的身份證號碼");
String line = new Scanner( System.in).nextLine();
System.out.print("原來你的身份證號碼是" + line.length() + "位數字啊");
}
}
其執行將不會報錯,結果如下