Reputation: 45
I have a switch within a while loop with many cases to run basic statistical analysis on a set of numbers. We're working on replacing the simple array of values with a map of arrays of doubles for multiple datasets that the user can add to. I have added an "add" case, and it can successfully add to the map... on every other run. So, when I write "add dataset 1 2 3 4 5" into the scanner, nothing happens, but if I write that into the scanner again, it will add successfully. Here's the important bit of code, let me know what you can make of it. getOption() is a method that gets a string via a scanner, splits it into individual words, and enter those words into an array of strings. The format of input is "case keyForMap valuesForMap". I know we shouldn't assume the user will follow this format, but we're letting it slide for this assignment. getValues() takes the numbers in the array, parses them to double, and adds them to a new array of doubles, which is returned.
HashMap<String,double[]> dataMap = new HashMap();
...
public void driver(){
Stats s = new Stats(data);
String[] options = getOption();
while (!"quit".equals(options[0])){
switch (options[0]) {
case "add": if (getOption().length < 2){
break;
}
else{
dataMap.put(options[1], getValues(options));
}
break;
case "summary": //Arrays.toString(dataMap.entrySet().toArray());
System.out.println(dataMap.containsKey("dsn"));
break;
case "quit": return;
default: System.out.println(options[0] + " is not a legal option");
}
options = getOption();
}
}
Upvotes: 0
Views: 65
Reputation: 5087
Replace if (getOption().length < 2)
with if (options.length < 2)
. Having the method call there means you're fetching a whole new line of input instead of using the one you already have, and then throwing it away after checking only its length.
Upvotes: 2