【问题标题】:Reading integer from user input using scanner使用扫描仪从用户输入中读取整数
【发布时间】:2014-05-11 03:25:19
【问题描述】:

在我正在创建的程序中,我正在为使用整数变量的用户创建一个菜单,当用户选择一个时,他们将在菜单中激活该选项。我正在尝试使用 readnextInt 但它不起作用,我不知道为什么。扫描仪的代码不起作用。

import java.util.Scanner;


 public class username
      {
    public static void main(String[] args)
{


    {   
       int Floor;
       Floor = 0;

       int Destination;
       Destination = 0;

       int UseLift;
       int AuditReport;
       int ExitLift;
       int a;


       UseLift = 1;
       AuditReport = 2;
       ExitLift = 3;
       a = read.NextInt;


       Scanner b = new Scanner(System.in);
       int a = in.nextInt();

       if (a == 1)
      System.out.println(" Enter your name ");

       else if (a == 2)
    System.out.println("");

       else if(a == 3)
    System.out.println(" Please Exit Lift ");

{

【问题讨论】:

  • 这甚至不能编译。您的 Scanner 实例名为 b 而不是 in
  • 这个a = read.NextInt;是什么??
  • 另外,大括号甚至没有正确放置或匹配。
  • @user3151959:命名约定与 JAVA 标准不兼容。

标签: java variables if-statement integer java.util.scanner


【解决方案1】:

首先,read 是什么?我没有看到它在任何地方被定义为Scanner

其次,一旦定义了read (Scanner read = new Scanner(System.in);),就可以调用nextInt(),而不是NextInt。所有方法在尝试调用它们时都需要这些括号。

【讨论】:

    【解决方案2】:

    这一行有你的错误。

    Scanner b = new Scanner(System.in);
    int a = in.nextInt();
    

    您的扫描仪称为 b,而不是 in。请改用 b.nextInt()

    Scanner b = new Scanner(System.in);
    int a = b.nextInt();
    

    您还有一个错误的 Read.nextInt(),并且您还没有定义 Read。我不认为该行试图做任何事情,所以删除它。

    【讨论】:

    • 我现在已经这样做了,但它一直要求我重命名一个。在 int a =b.nextInt();@Anubian Noob 下还有一条红线
    【解决方案3】:

    错误

    声明

    a = read.NextInt;
    

    似乎是多余的。变量read 未定义。

    a = read.NextInt;
    
    Scanner b = new Scanner(System.in);
    int a = in.nextInt();
    

    变量in 未定义,但用于读取nextInt()

    int a = in.nextInt();
    

    它必须指向Scanner 类的实例。将其替换为b

    您在同一范围内定义了两次a。因此,您的 IDE 必须在

    下显示 red
    int a;
    ...
    ...
    Scanner b = new Scanner(System.in);
    int a = in.nextInt();
    

    最后,不是错误,而是您的代码不遵循变量名和类名的 JAVA 命名约定。 更多详情请阅读Java Naming Conventions

    建议更正

    1. 删除a = read.nextInt;,因为它似乎是多余的。
    2. 删除int a;,因为您在Scanner 之后重新定义它 实例化。
    3. int a = in.nextInt(); 更改为int a = b.nextInt();

    【讨论】:

      【解决方案4】:

      其余代码是正确的,只需更改此行“int a = in.nextInt();”到“int a = b.nextInt();”因为 b 是您的扫描仪的名称,而 nextInt() 是属于 Scanner 类的方法“in.nextInt()”不正确。

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多