Java - 出现提示时无法收集字符串
Java - failing to collect a String when prompted
当我运行下面的代码在一个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'
),所以那里有一个空行等待被消耗。
当我运行下面的代码在一个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'
),所以那里有一个空行等待被消耗。