非常新的java,并想知道为什么即使扫描器的输入为“N”,这个while语句也不会结束,从而将表达式计算为false。
import java.util.*;
public class addSongs {
public static void main (String[]args){
Scanner songAdd = new Scanner(System.in);
Scanner addContinue = new Scanner(System.in);
String ceaseAdd = new String();
ceaseAdd = "Y";
while(ceaseAdd != "N")
System.out.println("Enter track title");
String newSong = songAdd.nextLine();
MP3_catalogue.title.add(newSong);
System.out.println("Enter artist name");
String newArtist = songAdd.nextLine();
MP3_catalogue.artist.add(newArtist);
System.out.println("Enter duration");
String newDuration = songAdd.nextLine();
MP3_catalogue.duration.add(newDuration);
System.out.println("Would you like to add another song? Y/N");
ceaseAdd = addContinue.nextLine().toUpperCase();
}
}
答案 0 :(得分:2)
除了已经指出的字符串检查。遗失{}
。正确缩进代码如下所示:
while(ceaseAdd != "N")
System.out.println("Enter track title");
String newSong = songAdd.nextLine();
MP3_catalogue.title.add(newSong);
System.out.println("Enter artist name");
没有{}
while
仅适用于第一行。它应该是这样的:
while(!ceaseAdd.equals("N")){
System.out.println("Enter track title");
String newSong = songAdd.nextLine();
MP3_catalogue.title.add(newSong);
System.out.println("Enter artist name");
String newArtist = songAdd.nextLine();
MP3_catalogue.artist.add(newArtist);
System.out.println("Enter duration");
String newDuration = songAdd.nextLine();
MP3_catalogue.duration.add(newDuration);
System.out.println("Would you like to add another song? Y/N");
ceaseAdd = addContinue.nextLine().toUpperCase();
}
答案 1 :(得分:0)
在java中,你不要将字符串与“==”进行比较。 “==”检查它是否是完全相同的对象,如果它具有相同的值则不会。 要检查它是否具有相同的文本,您必须使用
string.equals()
在您的示例中,它看起来像这样:
public static void main (String[]args){
Scanner songAdd = new Scanner(System.in);
Scanner addContinue = new Scanner(System.in);
String ceaseAdd = new String();
ceaseAdd = "Y";
while(!ceaseAdd.equals("N"))
System.out.println("Enter track title");
String newSong = songAdd.nextLine();
MP3_catalogue.title.add(newSong);
System.out.println("Enter artist name");
String newArtist = songAdd.nextLine();
MP3_catalogue.artist.add(newArtist);
System.out.println("Enter duration");
String newDuration = songAdd.nextLine();
MP3_catalogue.duration.add(newDuration);
System.out.println("Would you like to add another song? Y/N");
ceaseAdd = addContinue.nextLine().toUpperCase();
}