0

I want to take a String str and an int wSize and use it to create a hashtable. An example is the best way to explain what I want.

For example: str = "alphabet" wSize = 2

I want a hashtable that looks like this: al 0 lp 1 ph 2 ha 3 ab 4 be 5 et 6

This is what I have so far

public static void hashTableCreator (String str, int wSize) {
    Hashtable ht = new Hashtable();
    str = "alphabet";
    wSize = 2;
    String str2;

    for (int i = 0; i < str.length(); i++) {
      int value = 0;
      ht.put(str.substring(i, i + 1), value);
      value++;
    }

    Set set = ht.keySet(); 

    Iterator itr = set.iterator();
    while(itr.hasNext()) {
      str2 = (String) itr.next();
      System.out.println(str2 + ": " +
                         ht.get(str2));
    }

  }
3
  • I don't understand, you have parameters in your method, but you're setting values to them on the next line. Whats the point of the parameters? Commented Sep 22, 2012 at 22:00
  • The question is how would i go about implementing the thing I want. And the parameters are for later use, this is just an example I want to test. Commented Sep 22, 2012 at 22:05
  • You implemented it already, as you show in your question. So what's the real question? Commented Sep 22, 2012 at 22:18

2 Answers 2

2

in string.substring(a,b) first argument is zero indexed and 2nd argument is 1 indexed. for example:

      "smiles".substring(1, 5) returns "mile"

if you wanna get al from the string "alphabet" you'd have to do

         LinkedHashMap<String, Integer> ht = new LinkedHashMap<String, Integer>();
 int value=0;
     for(int i=0; i<str.length()-1; i++) {
         ht.put(str.substring(i, i+2), value);
         value++;
     }
     Set<String> set = ht.keySet();
     Iterator<String> itr = set.iterator();
     while(itr.hasNext()) {
         String d = itr.next();
         System.out.println(d+ " "+ ht.get(d));
     }
    }

OUTPUT: al 0 lp 1 ph 2 ha 3 ab 4 be 5 et 6

Sign up to request clarification or add additional context in comments.

2 Comments

I get String index out of bounds because when it gets to end I have an issue
In for: - (i < str.length() - 1)
0
int value = 0;
for (int i = 0; i < str.length()-1; i++) {
  ht.put(str.substring(i, i + 2), value);
  value++;
}

5 Comments

why are you initilizing value to 0 on every iteration ?
Thanks, I ran the code and got this ha: 3 lp: 1 be: 5 ab: 4 et: 6 al: 0 ph: 2
I want it be on order is that possible? You guys are awesome btw
Use LinkedHashMap if you want it to be ordered on insertion.
How would that work? Can you refer me to some reading material. THanks

Your Answer

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.