gpt4 book ai didi

Java - 提示时未能收集字符串

转载 作者:行者123 更新时间:2023-11-30 03:27:55 25 4
gpt4 key购买 nike

当我在 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.

最佳答案

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

关于Java - 提示时未能收集字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29727855/

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