I am using an array of arraylists to store words from a string. I am storing them in the array of array lists by the length of the word. I am using a switch statement right now, but I have to have 45 cases the way I am doing it, and I was wondering if anyone knew of an easier and shorter way that I could carry out the same operation. Here's some code:
String temp;
Scanner sc = new Scanner(str);
while(sc.hasNext())
{
temp = sc.next();
switch(temp.length()){
case 1:
wordsByLen[0].add(temp);
case 2:
wordsByLen[1].add(temp);
case 3:
wordsByLen[2].add(temp);
I have cases 1-45 and a default. I would just like to shorten this up, if possible. Thanks!
6 Answers 6
Don't bother with the switch, just do
wordsByLen[temp.length() - 1].add(temp)
Comments
String temp;
Scanner sc = new Scanner(str);
while(sc.hasNext())
{
temp = sc.next();
wordsByLen[temp.length()-1].add(temp);
}
Comments
wordsByLen[temp.length()].add(temp); --- this should do I guess.
Comments
Why do you need to use switch case over here. try this out :
String temp;
Scanner sc = new Scanner(str);
while(sc.hasNext())
{
temp = sc.next();
if(temp.length > 0) {
wordsByLen[temp.length()-1].add(temp)
}
Comments
Just use one shorter than the length
int len = temp.length();
wordsByLen[len - 1].add(temp);
Comments
Instead of switch you can simply use the following:
wordsByLen[temp.length()-1].add(temp);
List<List<String>>? You'd have to do alistlist.get(i).add(temp)...MultiMap<Integer, String>would be easier to use.