John Abraham
John Abraham

Reputation: 3

How to check whether a string's name in Java is the same as an integer's name?

For example, if the user enters "sword", the integer variable sword should change its value from 0 to 1. If the user enters "boots", the integer variable for boots should change from 0 to 1. I know I can do a manual if statement for each of these articles I want to check, but is there any possible way to check the string entered and change the respective variable's value without making an if statement for each article?

Upvotes: 0

Views: 63

Answers (2)

ifloop
ifloop

Reputation: 8386

This is possible by using reflection (Java Tutorials - Reflection) but a very inefficent and slow way. You should consider unsing a switch case statement or even better, a map:

Upvotes: 0

Makoto
Makoto

Reputation: 106470

Store your information inside of a map instead. When a user enters a string that you key off of (sword, boots, etc), then update its value.

public class DataClass {
    Map<String, Integer> data = new HashMap<>();

    public void addValueToData(String key) {
        if(!data.containsKey(key)) {
            data.put(key, 0);
        } else {
            data.put(key, data.get(key) + 1);
        }
    }
}

Upvotes: 5

Related Questions