【问题标题】:Java - failing to collect a String when promptedJava - 提示时无法收集字符串
【发布时间】:2015-04-19 09:03:36
【问题描述】:

当我在 do-while 循环中运行以下代码时(省略);它同时打印要求歌曲名称和大小的两行。但是,它在询问文件大小之前从不收集名称的字符串输入。

在询问文件大小之前,我需要它为名称收集一个字符串(这不会发生)。

这是怎么回事?

            //Interface.java
            import java.util.*;
            ...
            Scanner console = new Scanner(System.in); //After importing Scanner.
            ...

            option = console.nextInt(); // User chooses an option (add / delete song, etc.) by pressing a number. Only adding is relevant here.

            do { // Code inside a do-while loop which repeats for entering name / file size on 4 songs.
            song = console.nextInt(); // User chooses to add name / file size to either song1, song2, song3 or song 4 (there is a maximum of 4 song objects).

            System.out.println("Please enter the name of a song.");
            name = console.nextLine();

            System.out.println("Please enter file size in MB.");
            do { // This do-while checks input to be an integer / not negative & then it assigns the input as...
            fileSize = console.nextInt();
            // end of do-while loop which checks the integer.

            // end of do-while loop which lets user add name / size to a maximum of 4 songs.

【问题讨论】:

  • 请尝试提供“最少但可执行”的代码 sn-p。很难说发生了什么。不知道如何设置扫描仪...
  • 您的代码似乎运行良好:ideone.com/RJhwiZ
  • @maraca 在 OP 示例中没有 nextLine 放在 nextFoo 之后。
  • 当还有一个Console 时调用Scanner console 会让人感到困惑。

标签: java loops input java.util.scanner


【解决方案1】:

始终在console.nextInt(); 之后执行console.nextLine(); 以消耗换行符,它应该可以正常工作。见这里:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods 原因是nextInt() 不消耗换行符('\n'),所以那里有一个空行等待消耗。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 2019-07-04
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    相关资源
    最近更新 更多