簡體   English   中英

從用戶輸入返回一個“int”

[英]Return an "int" from user input

我正在 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();”處得到一個“InputMismatchException”。 在 main 和 "int dice = input.nextInt();" 在我的骰子方法中。 真的,我只是在尋找一個解釋。 我在我的教科書上查過,在別處查過,但我找不到解釋。

從我從您的問題中可以看出,這是因為Scanner不直觀。 您似乎在說它不會第二次等待輸入。 如果情況並非如此,則此答案無濟於事。

next()方法接受下一個以空格分隔的字符串,這意味着如果您鍵入
I want all these words
它會帶上I ,坐在前面的緩沖區里want all these words 因此,當您調用nextInt() ,它會接收下一個輸入,即want ,而不是 int。

因此,除非您確實只想要下一個單詞,否則請使用nextLine()而不是next() ,並在nextInt()之后調用nextLine() nextInt()以強制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;
   }
}

骰子方法期望返回一個 int 值。 當您在“每輪有多少角色?”這一行之后輸入一個值時。 打印確保您輸入的是 int 而不是另一種類型。 例如,值 1、2、3 是您的代碼所期望的,而不是一、二、三。

或者嘗試用 input.nextLine() 替換 input.nextInt()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM