2017-12-02 22 views
0

我正在嘗試編寫一個程序來統計音樂的音階。不幸的是,我遇到了一個問題。我需要一種方法來檢查輸入值是否是音階上的音符之一。如果是,請將其轉化爲數字以備後續計算。如果不是,則顯示錯誤並再次詢問。我試圖做到這一點,即使我給出有效的音符,它也會使我陷入無限循環。任何幫助? 我的代碼:Java檢查一個變量是否是A-G。如果不是,則顯示錯誤消息並再次詢問

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;  
    } 
} 
+0

不要使用'!='來比較字符串。改用'!note.equals(「A」)'。請參閱重複問題以獲取解釋。 – Jesper

回答

0

note != "A"這不是比較字符串的正確道路。使用equals()

if (!"A".equals(node)... 

這是因爲==!=比較引用,而不是對象的內容「。要按「內容」比較字符串,您需要使用equals()方法。

相關問題