Search code examples
javastringdictionaryvariablesstring-literals

efficient way to check if a group of letters in a string is a variable?


I am trying to write a code to print music scales. I cannot use a list or array type of structure (school reasons). here's what i have so far:

public class Musicarum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        double buildNum = 0.01;
        
        //**************************************************************************************
        int a = 1, bb = 2, b = 3, c = 4, db = 4, d = 5, eb = 6, e = 7, f = 8, gb = 9, ab = 10;
        //**************************************************************************************

then further in the code it will, once you select where you want to go, it should print a scale. right now i am on major scales:

if(answer.equals("scales")) {
                System.out.println("Would you like to see a major or a minor scale?");
                String scale = input.nextLine();
                scale = scale.toLowerCase();
                if(scale.equals("major"));
                System.out.println("What Scale would you like to see?");
                scale = input.nextLine();
                System.out.println("The scale you would like to see is made of the notes: " + scale.charAt(0));
}}

my current problem is in the line above last where i am printing the scale. I am wondering if it is possible to check the string scale and see if the words inside correspond to a variable that i predefined. i then want to be able to use the number value that i assigned to the variable. I have tried using the unicode value of the first character the user types, but i don't know how to use that to match to one of my int variables. I have also looked into setting up something similar to a python dictionary, but I'm completely at a loss for how to do that right now. any help? trying to do this without using 4000 nested if statements and 157 variables for each scale.


Solution

  • Java isnt a dynamic language, so taking a user string and "translating" that into a variable name is (albeit possible) extremely burdensome (and a very advanced topic).

    The straight forward answer to your problem is to use the Map structure (maps are Java's equivalent of python's dicts). A quick example:

    Map<String, Integer> scaleByName = new HashMap<>();
    scaleByName.put("a", 1); 
    scaleByName.put("bb", 2); ...
    

    Then you can use calls like scaleByName.get(someStringComingFromUserInput) to map the string key to its Integer value. There is plenty of javadoc that tells you more how to use maps.