[英]Connecting a Scanner object to a System.in object and using Scanner methods
這是我的問題:
我正在嘗試使用Scanner和System.in從鍵盤獲取輸入並將其分配給int變量。
這就是我所擁有的(完整的程序包含在下面):
// this program will use scanner objects and system inputs
public class Scanner
{
public static void main(String[] args)
{
int number;
// declares integer "number"
Scanner keyboard = new Scanner(System.in);
//-------------------------------------------------------------------
// declares referance variable (Scanner class) "keyboard", creates
// Scanner object that
// reads input from System.in, then assigns address of Scanner object
// to the reference variable "keyboard"
//-------------------------------------------------------------------
System.out.println("Enter an integer value: ");
// displays text
number = keyboard.nextInt();
// assigns keyboard input to "number" as integer value
System.out.println("You entered the integer " + number);
// displays "number" to see if the program worked
}
}
當我嘗試使用javac在Windows命令提示符下編譯程序時,出現以下錯誤消息:
error: constructor Scanner in class Scanner
cannot be applied to given types;
Scanner keyboard = new Scanner(System.in);
required: no arguments
found: InputStream
reason: actual and formal argument lists differ in length
error: cannot find symbol
number = keyboard.nextInt();
^
symbol: method nextInt()
location: variable keyboard of type Scanner
2 errors
我究竟做錯了什么?
有一個命名沖突 。 從Java語言的角度來看,您必須使Scanner
類具有唯一性,可以通過以下兩種方法進行:
使Scanner
類明確
通過使用全限定名
public static void main(String[] args) { int number; java.util.Scanner keyboard = new java.util.Scanner(System.in); System.out.println("Enter an integer value: "); number = keyboard.nextInt(); System.out.println("You entered the integer " + number); }
您應該重命名類Scanner-錯誤是,您使用Java標准庫中名稱為Scanner的類。
import java.util.Scanner;
public class Main {
public static void main(String[] args){
int number;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer value: ");
number = keyboard.nextInt();
System.out.println("You entered the integer " + number);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.