(In java,) This may or may not be possible, I assume it is because it seems to short-cutty/easy to not exist. Basically what I want to do is have the user insert the name of a state, then it add one to that state's counter, which is stored in a different class. I want to do this without creating 50 if/else statements. Here's pseudocode which represents how I would expect it to be done. (this code would be encapsuled in a while loop in mainclass.java and the counters and state names are in a class named state.java.)
Scanner userstate = new Scanner(System.in);
String statename = userstate.nextLine();
state.(statename).counter++;
in state.java:
public state(int counter){
}
public static state Alabama = new state(0);
For time's sake, I hope there is a shortcut similar to the above.
The preferred way in this case would be to store the states in a HashMap or similar. This allows you to look up a state by name:
import java.util.*;
class State
{
static HashMap<String, State> states = new HashMap<String, State>();
public static State Alabama = new State("Alabama", 0);
public State(String name, int counter)
{
// [ init... ]
states.put(name, this); // add this state to the collection of states
}
public static State getByName(String name)
{
return states.get(name);
}
}
Then your code could look like this:
State.getByName(statename).counter++;
You could also use reflection , but that should be avoided where possible.
You don't want to try looking up variables by their Java names (eg, "Alabama"); this is possible but much more complicated than you want to deal with.
If you can use external libraries, this is a perfect fit for a Guava Multiset
, which keeps track of how many times a certain element has been seen. Otherwise, you probably want a Map<String,Integer>
from the state name to a counter. (Note that you'll have to put(get()+1)
in that case; ++
won't work.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.