0

I'm trying to write a program to count up and down the musical scale. Unfortunately, I have ran into a problem. I need a way to check if the input value is one of the notes on the musical scale. If it is, turn it into a number for later calculations. If not, display an error and ask again. I tried to do this and it puts me in an infinite loop even when i give a valid note. Any help? My code:

    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;       
    }
}
reticivis
  • 489
  • 2
  • 7
  • 13
  • Don't use `!=` to compare strings. Use `!note.equals("A")` instead. See the duplicate question for an explanation. – Jesper Dec 02 '17 at 19:01

1 Answers1

0

note != "A" that's not a correct way to compare strings. Use equals():

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

That's because == and != compare references and not objects 'contents'. To compare strings by 'contents', you need to use equals() method.

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72