【问题标题】:Return an "int" from user input从用户输入返回一个“int”
【发布时间】:2018-02-19 17:45:34
【问题描述】:

我正在用 java 程序(特别是 jGRASP)开发一个骰子游戏,它正在踢我的罐子。我需要从用户输入中返回名称和每手骰子的数量。到目前为止,这是我的(相关)代码:

import java.util.*; 

public class DiceGame {
   public static Scanner input = new Scanner(System.in);

   public static void main(String[] args) {
      System.out.println("Welcom to the Lab 7 Dice Game.");
      name();
      dice();
   }
   public static String name(){
      System.out.print("What is you name? ");
      String name = input.next();
      return name;
   }
   public static int dice(){
      System.out.print("How many rolls per round? ");
      int dice = input.nextInt();
      return dice;
   }
}

该方法提供了我的输入行并要求用户输入字符串作为名称。这工作得很好,它会按预期打印出来。但是当它继续调用 dice 方法时,我在“dice();”处得到一个“InputMismatchException”。在 main 和 "int dice = input.nextInt();"在我的骰子方法中。真的,我只是在寻找一个解释。我在我的教科书中查过,在其他地方也查过,但找不到解释。

【问题讨论】:

  • 在此行之后拨打input.nextLine()int dice = input.nextInt();
  • 或者你也可以这样做 Scanner input = new Scanner(System.in).useDelimiter("\\s+"); 它将忽略标记之间的任何空白(包括换行符)。
  • 我的错,那行是在name() 方法中的input.next 之后...(并且您应该为您的方法使用更好的名称,因为name() 听起来更像是一个变量而不是一个方法,方法名称应以动词开头)。每当您调用next() 时,Scanner 类仍在等待另一个从未读取的参​​数,因为它希望它位于同一行。当您添加该行input.nextLine() 时,您明确告诉Scanner 在按下Enter 后读取下一行中的下一个标记

标签: java


【解决方案1】:

从您的问题中我可以看出,这是因为 Scanner 不直观。您似乎在说它第二次不等待输入。如果不是这样,这个答案是没有帮助的。

next() 方法接收下一个以空格分隔的字符串,这意味着如果您键入
I want all these words
它将接收I,缓冲区位于want all these words 前面。所以,当你调用nextInt() 时,它会接受下一个输入,即want,这不是一个int。

因此,除非您真的只想要下一个单词,否则请使用nextLine() 而不是next(),并在nextInt() 之后调用nextLine() 以强制Scanner 使用换行符。

import java.util.*; 

public class DiceGame {
   public static Scanner input = new Scanner(System.in);

   public static void main(String[] args) {
      System.out.println("Welcome to the Lab 7 Dice Game.");
      name();
      dice();
   }
   public static String name(){
      System.out.print("What is your name? ");
      String name = input.nextLine();
      return name;
   }
   public static int dice(){
      System.out.print("How many rolls per round? ");
      int dice = input.nextInt();
      input.nextLine();
      return dice;
   }
}

【讨论】:

    【解决方案2】:

    dice 方法期望返回一个 int 值。当您在“每轮有多少个角色?”行之后输入一个值时打印确保您输入的是 int 而不是其他类型。例如,值 1、2、3 是您的代码所期望的,而不是一、二、三。

    或者尝试将 input.nextInt() 替换为 input.nextLine()

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 1970-01-01
      • 2015-04-02
      • 2013-02-19
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多