我正在尝试编写一个程序来计算音阶。不幸的是,我遇到了一个问题。我需要一种方法来检查输入值是否是音阶上的音符之一。如果是,请将其转换为数字以供以后计算。如果没有,则显示错误并再次询问。我尝试这样做,即使我给出了有效的注释,它也会使我陷入无限循环。有什么帮助吗?我的代码:
package music;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class musicc {
public static void main(String[] args) throws Exception {
int noteid;
noteid = musicc.getNoteId();
}
public static int getNoteId() {
String note = "0";
int returnValue = 0;
note = (String)JOptionPane.showInputDialog(null,"What note do you want to start on?",JOptionPane.PLAIN_MESSAGE);
while (note != "A" && note != "B" && note != "C" && note != "D" && note != "E" && note != "F" && note != "G") {
JOptionPane.showMessageDialog(null, note + " is not a valid note! Try again.", "Invalid note!", JOptionPane.ERROR_MESSAGE);
note = (String)JOptionPane.showInputDialog(null,"What note do you want to start on?",JOptionPane.PLAIN_MESSAGE);
}
switch(note) {
case "A":return 1;
case "B":return 2;
case "C":return 3;
case "D":return 4;
case "E":return 5;
case "F":return 6;
case "G":return 7;
}
return 0;
}
}
note != "A"
这不是比较字符串的正确方法。使用equals()
:
if (!"A".equals(node)...
那是因为==
and!=
比较引用而不是对象“内容”。要按“内容”比较字符串,您需要使用equals()
方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句