gpt4 book ai didi

如果函数不起作用的 Java 扫描器

转载 作者:行者123 更新时间:2023-11-30 04:06:04 29 4
gpt4 key购买 nike

现在选择菜单上的每个选项都可以正常工作(感谢 Tarek Salah 和 dasblinkenlight 的帮助)。现在的问题是,当我选择一个需要我输入新单词的选项(例如选项 3,用户必须输入歌曲名称)时,它会跳过该选项并返回到菜单。有谁知道如何阻止这种情况发生,以便用户可以实际输入某些内容?

import java.util.Scanner;
public class JukeboxApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Jukebox jb = new Jukebox();
boolean check = false;
System.out.println("Please enter the corresponding number to perform said action.");
while ( check == false ) {
System.out.println("1: Add a song to the JukeBox\n" +
"2: Remove a song from the JukeBox\n" +
"3: Search for a specific song\n" +
"4: Display total price to play all songs\n" +
"5: Display the most expensive song\n" +
"6: Display the shortest song\n" +
"7: Display the most played song\n" +
"8: Display all songs in the JukeBox\n" +
"9: Display all songs by a specific artist\n" +
"10:\n" +
"11: Exit the JukeBox");
int num = sc.nextInt();
if ( num == 1 ) {
System.out.println("Please enter the name of the artist");
String artist = sc.next();
sc.nextLine();
System.out.println("Please enter the title of the song");
String title = sc.nextLine();
System.out.println("Please enter the price of the song");
double price = sc.nextDouble();
System.out.println("Please enter the length of the song");
double length = sc.nextDouble();
Song s1 = new Song(artist, title, price, length);
jb.addSong(s1);
} else if ( num == 2 ) {
System.out.println("Please enter the title of the song you would like to remove");
sc.nextLine();
jb.removeSong(sc.nextLine());
} else if ( num == 3 ) {
System.out.println("Enter the title of the song you are searching for");
jb.searchSong(sc.nextLine());
} else if ( num == 4 ) {
System.out.println(jb.calcTotal());
} else if ( num == 5 ) {
System.out.println(jb.showMostExpensive());
} else if ( num == 6 ) {
System.out.println(jb.showShortest());
} else if ( num == 7 ) {
System.out.println(jb.mostPlayed());
} else if ( num == 8 ) {
jb.displaySongs();
} else if ( num == 9 ) {
System.out.println("Please enter the artist you are searching for");
System.out.println(jb.searchArtist(sc.nextLine()));
} else if ( num == 10 ) {
System.out.println("");
} else if ( num == 11 ) {
System.out.println("Thank you for using my JukeBox.");
check = true;
}
}
}

}

最佳答案

这不起作用的原因是,当您希望用户仅输入一个值时,您可能会多次调用 sc.nextInt()

您应该将结果存储在变量中,并在所有 if 语句中使用该变量。或者,您可以使用 switch 语句。

var userEntry = sc.nextInt();
sc.nextLine(); // skip to the end of the line
if ( userEntry == 1 ) {
...
} else if ( userEntry == 2 ) {
...
} else if ( userEntry == 3 ) {
...
} else ...

var userEntry = sc.nextInt();
sc.nextLine(); // skip to the end of the line
switch ( userEntry ) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
default:
...
break;
}

关于如果函数不起作用的 Java 扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20691697/

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