gpt4 book ai didi

java - 将 Scanner 对象连接到 System.in 对象并使用 Scanner 方法

转载 作者:行者123 更新时间:2023-12-01 11:58:17 26 4
gpt4 key购买 nike

这是我的问题:

我正在尝试使用 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 类独一无二,有 2 个选项可以做到这一点:

  1. 重命名类(class)
    • 改成其他名称,这样就不会再出现命名冲突
  2. 使 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);
      }

关于java - 将 Scanner 对象连接到 System.in 对象并使用 Scanner 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28188495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com