循环Java在出现提示时无法收集字符串
当我在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.
# 1 楼答案
始终在
console.nextInt();
之后执行console.nextLine();
以使用换行符,它应该可以正常工作。请参见此处:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods原因是nextInt()
不使用换行符('\n'
),因此有一个空行等待使用