0

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!

asked Mar 21, 2013 at 16:25
4
  • You want to execute each case? If not write break after each case. Commented Mar 21, 2013 at 16:27
  • Why not List<List<String>>? You'd have to do a listlist.get(i).add(temp)... Commented Mar 21, 2013 at 16:27
  • Why not Map<Integer,List<String>>? No need to predefine. Commented Mar 21, 2013 at 16:28
  • @CPerkins: A MultiMap<Integer, String> would be easier to use. Commented Mar 21, 2013 at 16:29

6 Answers 6

3

Don't bother with the switch, just do

wordsByLen[temp.length() - 1].add(temp)
answered Mar 21, 2013 at 16:27
Sign up to request clarification or add additional context in comments.

Comments

3
String temp;
Scanner sc = new Scanner(str);
while(sc.hasNext())
{
 temp = sc.next();
 wordsByLen[temp.length()-1].add(temp);
}
answered Mar 21, 2013 at 16:28

Comments

3

wordsByLen[temp.length()].add(temp); --- this should do I guess.

Ajinkya
22.7k33 gold badges113 silver badges164 bronze badges
answered Mar 21, 2013 at 16:27

Comments

2

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)
 }
answered Mar 21, 2013 at 16:29

Comments

2

Just use one shorter than the length

int len = temp.length();
wordsByLen[len - 1].add(temp);
answered Mar 21, 2013 at 16:27

Comments

1

Instead of switch you can simply use the following:

wordsByLen[temp.length()-1].add(temp);
answered Mar 21, 2013 at 16:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.