Reputation: 11
I'm writing a program about musical chords. I want the user to input A-G or a-g, but it can also be # or - (flat), and also m (minor). It's running, but if you put in a#m, you get
Enter a musical piano chord name: A
I need it to keep reading the if statements so that if the input is 3 characters, I can delineate what that char should be.
I haven't added the section on sharps and flats yet.
import java.util.Scanner;
public class Hwk9 {
public static void main(String[] args) {
String chord;
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a musical piano chord name: ");
chord = stdin.nextLine();
String finalChord = validChord(chord);
System.out.println(finalChord);
}
public static String validChord(String input) {
if (input.length() > 3 && input.length() < 1) {
input = "Invalid chord";
}
char note = input.charAt(0);
char capNote = chordCapitalize(note);
if (capNote == 'A') {
input = capNote + "";
}
else if (capNote == 'B') {
input = capNote + "";
}
else if (capNote == 'C') {
input = capNote + "";
}
else if (capNote == 'D') {
input = capNote + "";
}
else if (capNote == 'E') {
input = capNote + "";
}
else if (capNote == 'F') {
input = capNote + "";
}
else if (capNote == 'G') {
input = capNote + "";
}
else {
input = "Invalid chord";
}
if (input.length() == 3) { *<<<<<<This section is not going through*
char minor = input.charAt(2);
if (minor == 'm') {
input = capNote + "" + minor;
}
else {
input = "Invalid chord";
}
}
return input;
}
public static char chordCapitalize(char input) {
String note = input + "";
String caps = note.toUpperCase();
char capNote = caps.charAt(0);
return capNote;
}
}
Upvotes: 0
Views: 121
Reputation: 17890
The problem is you are assigning the capitalized chord back to input
in the if
blocks. You need to have a local variable for that and not re-assign it to input
If you assign input
the value of capNote
, length of input
will always be one.
String result;
if (capNote == 'A') {
result = capNote + "";
}
else if (capNote == 'B') {
result = capNote + "";
}
//Rest of code
if (input.length() == 3) {
char minor = input.charAt(2);
if (minor == 'm') {
result = capNote + "" + minor;
}
else {
result = "Invalid chord";
}
}
return result;
Upvotes: 1