对 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();
}
}
最佳答案
除了已经指出的字符串检查之外。缺少 {}
。正确缩进的代码如下所示:
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();
}
关于java - 尽管评估错误,但扫描仪表达式的 while 循环仍在继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20153124/