Producing a string of 3 random letters for a hash table

I'm pretty new to all this and i was wondering if anyone would be able to help me produce a random string of 3 letters to be inputted into a hash table. I already have the code for integers to be placed into the table but am having difficulty with letters. I've tried using the Random() function but am probably putting it into the wrong place.
I will place the code underneath so you can all have a look at it.
Any help would be greatly appreciated.
Thanks in advance
Code:
class HashTable
private DataItem[] hashArray; // array holds hash table
private int arraySize;
private DataItem nonItem; // for deleted items
public HashTable(int size) // constructor
arraySize = size;
hashArray = new DataItem[arraySize];
nonItem = new DataItem(-1); // deleted item key is -1
public void displayTable()
System.out.print("Table: ");
for(int j=0; j<arraySize; j++)
if(hashArray[j] != null)
System.out.print(hashArray[j].getKey() + " ");
else
System.out.print("** ");
System.out.println("");
public int hashFunc(int key)
return key % arraySize; // hash function
public void insert(DataItem item) // insert a DataItem
// (assumes table not full)
int key = item.getKey(); // extract key
int hashVal = hashFunc(key); // hash the key
// until empty cell or -1,
while(hashArray[hashVal] != null &&
hashArray[hashVal].getKey() != -1)
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
hashArray[hashVal] = item; // insert item
} // end insert()
public DataItem delete(int key) // delete a DataItem
int hashVal = hashFunc(key); // hash the key
while(hashArray[hashVal] != null) // until empty cell,
{                               // found the key?
if(hashArray[hashVal].getKey() == key)
DataItem temp = hashArray[hashVal]; // save item
hashArray[hashVal] = nonItem; // delete item
return temp; // return item
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
return null; // can't find item
} // end delete()
public DataItem find(int key) // find item with key
int hashVal = hashFunc(key); // hash the key
while(hashArray[hashVal] != null) // until empty cell,
{                               // found the key?
if(hashArray[hashVal].getKey() == key)
return hashArray[hashVal]; // yes, return item
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
return null; // can't find item
} // end class HashTable
class HashTableApp
public static void main(String[] args) throws IOException
DataItem aDataItem;
int aKey, size, n, keysPerCell;
// get sizes
System.out.print("Enter size of hash table: ");
size = getInt();
System.out.print("Enter initial number of items: ");
n = getInt();
keysPerCell = 10;
// make table
HashTable theHashTable = new HashTable(size);
for(int j=0; j<n; j++) // insert data
aKey = (int)(java.lang.Math.random() *
keysPerCell * size);
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
while(true) // interact with user
System.out.print("Enter first letter of ");
System.out.print("show, insert, delete, or find: ");
char choice = getChar();
switch(choice)
case 's':
theHashTable.displayTable();
break;
case 'i':
System.out.print("Enter key value to insert: ");
aKey = getInt();
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
break;
case 'd':
System.out.print("Enter key value to delete: ");
aKey = getInt();
theHashTable.delete(aKey);
break;
case 'f':
System.out.print("Enter key value to find: ");
aKey = getInt();
aDataItem = theHashTable.find(aKey);
if(aDataItem != null)
System.out.println("Found " + aKey);
else
System.out.println("Could not find " + aKey);
break;
default:
System.out.print("Invalid entry\n");
} // end switch
} // end while
} // end main()
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static char getChar() throws IOException
String s = getString();
return s.charAt(0);
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);
} // end class HashTableApp

public class Foo {
    private java.util.Random rand = new Random();
    public static void main(String[] args) throws Exception {
        new Foo().go();
    void go() throws Exception {
        String allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        System.out.println(getRandomString(allowedChars, 3));               
    String getRandomString(String allowedChars, int length) {
        StringBuffer buf = new StringBuffer();
        int charCount = allowedChars.length();
        for (int count = 0; count < length; count++) {
            int index = rand.nextInt(charCount);
            buf.append(allowedChars.charAt(index));
        return buf.toString();
}

Similar Messages

  • Select for a hashed table

    Hi All,
    This is a repost but this time Ill be specific.
    How do I select from a table into a hashed table faster without using "select distinct"? my primary concern is the speed of the select statement, and im afraid I cannot get rid of the hashed table destination.
    Thanks,
    Kenny

    HI Kenny,
    HASHED TABLE:
    There is no default setting for hashed tables. However, you must define a UNIQUE key. The NON-UNIQUE addition is not permitted.
    You cannot avoid this statement. May be the alternative is You have to use SORTED table with NON-UNIQUE option and then apply DELETE ADJACENT DUPLICATES, in this way you can have unique values for your itab.
    Regards,
    Raghav

  • Linking a Hash-table & a string

    I've got a hashtable containing information pertaining to a certain String object. This string object is not unique, and also the way to differentiate them is using the string and also the information in the hash table.
    I want to link up the String & the hashtable so that they can related.

    Huh?
    Put both into a Hashmap... or a wrapper object. Or whatever...

  • Iterarator for hash table.

    im having problems implementing an iterator for a hash table. I have an int value called pointer, which would move down the table. when i try to call next() it returns the very first element at index 0 in the hash table. then it moves until it finds a next element and returns it. The problem is that the cursor should be at an element position when i call next() and not at index 0 which is null.
    public class myIterator implements Iterator
              public int pointer;
              public myIterator()
                   pointer = 0;
                   while(hasNext() && table[pointer] != null)
                        pointer++;
    public boolean hasNext()
                   //System.out.println(cursor);
                        //System.out.println(table.length);
                        /*if(cursor > table.length-1)
                             return false;
                        return true;
                             if(cursor >= table.length)
                             return false;
                        return true;
              * This method returns the next element, if any.
              * @return the next element.
              public Object next()
                   Object temp = null;
                   if(!hasNext())
    throw new NoSuchElementException();
                   else
                        System.out.println("cursor " + cursor);
                        temp = table[cursor];
                        cursor++;
                        if(hasNext())
                             while(table[cursor] == null)
                                  cursor++;
                        return temp;
              }

    You haven't even provided something with valid syntax - where is this "cursor" variable defined? And in one method you are using and incrementing something called "pointer", and somewhere else "cursor", so maybe you're mixing two different variables but trying to use them for the same purpose and they are out of sync.

  • Macbook Pro's keyboard is typing random letters/symbols- can't figure out- HELP!

    OK, so everything was just fine, worked wonderfully, then I found my little chihuahua puppy walking on the keyboard, she is very tiny, so not heavy at all, & I caught it pretty quick... I DID see she may have had a little bit of wetness on the bottom of a paw, as there was a bit here or there, but it really wasn't much at all, and I was able to soak it all right up with a tissue, it really wasn't enough water, or in a bad enough spot, for me to worry at all about any damage being done- however- while trying to enter text in text edit, I realized that all the keys on my keyboard were either not responding at all, or typing completely random letters/symbols instead of the intended characters-  for example, every time I'd type/press one single letter on the keyboard, one time, instead of that letter, it would type TWO completely different letters, like 'ht' , at the same time- so every "d" would produce "ht" over and over... sometimes it looks like hebrew or russian letters, I don't even know! So I'm pretty darn sure my puppy must have typed some crazy key combo that did, well, who knows what- I've tried looking this up here on these forums, for a couple days now, and thought that I maybe figured it out a couple of times, but nope- no luck. It isn't my language setting, my option key isn't stuck, I'm lost! I saw a couple people who seemed to know what they were talking about, who were trying to help others with similar problems, and they asked the person to enter "asdfg" into text edit, and to post what that produced instead of the "asdfg" so.... I planned on doing that very thing right now, but there seems to have been a new development- as now, when I go into text edit, none of my keys work/respond when hit- except for a few, the following keys in lower case ";" " ' " "/" "[" "]"
    "\" "=" & "-" THEN, when I hit the following keys, here's what they type:
    c= cde3  
    v= frv4
    b= bgt5
    n= hny6
    m= jmu7
    comma= ik8,
    period= lo9.
    Then sometimes, when I hit the 1 or 2 key, the letter "z" starts to type constantly filling up the whole text edit box, like, "zzzzzzzzzzzzzzzzzzzzzzzzzz.... & so on"
    If anyone has any idea what is really going on here, PLEASE help me out- I love & need this laptop for work, school, etc. and right now, I am no where near an apple store, don't even have good phone reception up here- (on a mountain!) so I'm really hoping that someone can help me figure this out once and for all! THANK YOU for reading this lengthy post, & thanks in advance to anyone who tries to solve this mystery!

    I should point out I was having a very similar issue with no known liquid coming in contact with the machine. The keys that were affected were close together: my e, d, and c keys would consistantly type weird combinations of characters, some of them very out there, stuff like ¥©þ®. An external keyboard would work fine.
    After a few days it just stopped, and the only reason I can think of is that overheating was the problem. I was playing "cookie clicker" a game where you often leave the game running overnight, and I noticed that the fan was often working very hard and that the computer got pretty warm, even when leaving it on a hard surface. So after three days of symptoms I stopped playing that game and a day or two later everything was back to normal. My e, d, and c keys were inconsistant for the first 24 hours (sometimes worked, sometimes didn't), but now they're working working fine.

  • HT201991 When I review an app, my 'name' shows up as just a bunch of random letters.

    I noticed that if I review an app, my name shows up as just a string of random letters like "BJKCLCJDOIOSUODIDJDJLD"
    I also noticed that it seems everyone else's review name shows up as at least something that reads like a nickname.
    I have tried finding help on why this is but cannot. Can anyone help me here? My apple id is my email address and not sure there's any way to change that.
    Thanks for any help!

    I have an iPhone 6 and have been having this issue since I got it in December 2014. Apps open on their own, scrolling up and down, etc. It's like a ghost is touching the screen. It seems to be the worst when my Verizon connection is only at 3G or my wifi strength is low. I'm not sure if it's an iPhone thing or a carrier issue?? Any ideas?

  • »HP 15-g019wm Notebook PC (ENERGY STAR) Laptop types groups of random letters

     »HP 15-g019wm Notebook PC (ENERGY STAR)   How do i get my laptop keyboard to work correctly so that it is not typing groups of random letters every time i type a letter. It says that it is working correctly.  It works fine with a wireless mouse and  keyboard  If I attach my wireless mouse and keyboard I am able to type without it happening. I need to make this work correctly and when the device is checked it says that it is working correctly.  I have tried using  canned air to see if something   is stuck inside  under the keyboard.

    Hello jkriz1960,
    Welcome to the HP Forums, I hope you enjoy your experience! To help you get the most out of the HP Forums I would like to direct your attention to the HP Forums Guide First Time Here? Learn How to Post and More.
    I have read your post on how your keyboard is producing random groups of letters every time you type, and I would be happy to help in this endeavor!
    Since you have successfully tested a secondary keyboard, I recommend following this document on Notebook Keyboard Troubleshooting (Windows 8). This resource should help you synchronize the keyboard correctly with the rest of the computer. 
    Please re-post with the results of your troubleshooting, and I look forward to your reply!
    Regards   
    MechPilot
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos, Thumbs Up" on the right to say “Thanks” for helping!

  • Keyboard problem typing random letters and symbols

    I'm having a keyboard problem, the g key, t key, and 5 key type random letters and symbols.  i just spent $700 a few monoths ago to a genius [at getting my money] for a logic board after spillin somethin on it.  didnt spill anyqthing time.  shoot.  is this goin to be another major expenditure?  downloaded os x 9.4, hoping that might somehow cure it.  yeah right

    Hi Rob,
    Welcome to Apple Support Communities.
    It sounds like your running into an issue with the keyboard on your MacBook Pro. The article linked below provides suggestions that will resolve most keyboard issues like the one you described.
    OS X Mavericks: If keys on your keyboard don’t work
    http://support.apple.com/kb/PH13809
    If other keys don’t work
    You may have accidentally set an option that changes how your keyboard operates.
    Choose Apple menu > System Preferences, click Dictation & Speech, then click “Text to Speech.” If “Speak selected text when the key is pressed” is selected, deselect it or click Change Key to select another key.
    Choose Apple menu > System Preferences, click Accessibility, then click Keyboard. Make sure Slow Keys is turned off. If Slow Keys is on, you must hold down a key longer than usual before it’s recognized.
    Choose Apple menu > System Preferences, click Accessibility, then click Mouse & Trackpad. Make sure Mouse Keys is off. If Mouse Keys is on, pressing keys in the numeric keypad moves the pointer instead of entering numbers.
    Choose Apple menu > System Preferences, click Keyboard, then click Input Sources. Select “Show Input menu in menu bar.” Open the Input menu and make sure the correct keyboard layout is selected. To see the keyboard layout, click Keyboard, then choose “Show Keyboard & Character Viewers in menu bar.”
    I hope this helps.
    -Jason

  • Random letters added to my url - any ideas?

    Hi Guys
    On this particular site we started seeing funny random letters and numbers added to our urls - we did not touch these pages in quite a while and it only started about a week ago.  Even if you change the url in "SEO" etc... it automatically adds it.
    Any ideas?
    See http://tonipizza.co.za/Tonis_Pizza_Menu.html#.UbIe3JU56YU
    it should read http://tonipizza.co.za/Tonis_Pizza_Menu.html
    Support says it might be one of our scripts that "broke"  -- but sounds like a bit of a stretch to me.  Again, we have not touched code on this  page for a loooong time.
    Thanks
    Casper

    Hey Casper,
    There's some sort of conflict with a content holder you have placed within the page.  When you remove it the url restores back to normal. 
    I would look into this script in the "add this" content holder which most likely is affecting the output of the url.
    Kind regards,
    -Sidney

  • Random order for slide show?

    I have a lot of pictures in an album that I would like put in random order for a slide show. I want to burn that to a dvd to play at our day care centers (pics of the kids throughout the summer). is there any way to do this other than dragging and dropping the pictures manually? that takes a lot of time.

    OK. Well here's a helpful answer. Someone's already written a quick Applescript for adding random numbers to every file in a folder. I added a little bit to the beginning and the end to let you be able to just drag and drop the folder onto the file, but give full credit to the poster
    Steps:
    (1) Open the Applescript Editor:
    Finder->Applications->Apple Script->Script Editor.app
    (2) In a new Script copy and paste the following text:
    --start copying
    on open the_Droppings
    tell application "Finder"
    set separator to ("_") as text
    set source to the_Droppings as alias
    set destination to make new folder at source with properties {name:"Shuffled"}
    set shuffle_pool to duplicate files of source to destination
    set shuffle_count to count shuffle_pool
    set duplicates to {}
    repeat with shuffle_file in shuffle_pool
    repeat
    set an_item to random number from 1 to shuffle_count
    if an_item is not in duplicates then exit repeat
    end repeat
    shuffle_file as alias
    set name of result to an_item & separator & name of result as string
    set end of duplicates to an_item
    end repeat
    end tell
    end open
    -- stop pasting here
    (3) File->Save As
    (4) Type in a name for the file and IMPORTANT save it as an application.
    (5) Place all the images that you want to randomize into any folder. (In iPhoto6: File->Export from an album or; in iPhoto5: Share->Export)
    (6) Drag the folder with your images onto the little application that you saved from the Script Editor
    (7) The Script will create a new folder inside whatever folder you dropped on it called "Shuffled".
    (8) Now if you do an Edit->Add Slideshow in iDVD you can just drag the contents of the Shuffled folder to iDVD and you're done! It'll make a DVD in seconds! Now if only you could set the time to more than 10 seconds!
    ALL CREDIT TO: http://forums.macosxhints.com/showthread.php?t=46359
    and
    http://macscripter.net/articles/4670_10_0C/

  • When printing from Firefox I get random letters, numbers, boxes.

    This happens when I print from email and Firefox. Sometimes I get the random letters, numbers and boxes with a small phrase with correct spelling. For example, this happened when I tried to fill out a US passport form. The form itself was okay. What I typed in printed with the random letters, numbers, boxes except for my husband's occupation. That printed okay.

    How do I do a screenshot? Sorry, I am not very computer literate.
    Another problem. Since I changed to UTF 16BE we no longer can access our bank account. It allows us to log in but goes to the squares, letters, and numbers when we open the account statement. I am not sure what the code was before I switched to UTF 16 BE.

  • I am unable to control my iPad 2. It is generating random letters when typing and when I try to delete it generates more letters unless I go slowly! Any advice?

    I am unable to control my iPad 2. When typing and deleting it generates random letters! Any advice

    Start with this and see how it goes. Quit all apps completely and reboot the iPad.
    Go to the home screen first by tapping the home button. Double tap the home button and the recents tray will appear with all of your recent apps displayed at the bottom. Tap and hold down on any app icon until it begins to wiggle. Tap the minus sign in the upper left corner of the app that you want to close. Tap the home button or anywhere above the task bar.
    Reboot the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider if it appears on the screen - let go of the buttons. Let the iPad start up.

  • ¿How to fill an array with random letters?

    Hello, I was wondering If filling a bidimensional array
    (8x10 for example) with random letters could be done in C#, I've tried tons of stuff, but I can't manage to do it. Thanks in advance.

    I was wondering If filling a bidimensional array
    (8x10 for example) with random letters could be done in C#, I've tried tons of stuff, but I can't manage to do it.
    >I was wondering If filling a bidimensional array (8x10 for example) with random letters
    >could be done in C#,
    Yes.
    >I've tried tons of stuff, but I can't manage to do it.
    With exactly which part of this assignment are you having trouble?
    Can you create a 2-dim array of characters?
    Can you generate a random letter?
    Show the code you have written so far.
    Don't expect others to write a complete solution for you.
    Don't expect others to guess as to which part you're having difficulty with.
    Show the code you have working, and the code which you have tried which isn't working,
    Explain what is happening with it which shouldn't.
     - Wayne

  • API to generate an image of random letters?

    Is there a free Java API for generating those images of random letters used to ensure that a human has submitted a web form?
    I know it's not too hard to write from scratch, but I'd like to save myself the work :)

    it's called a "captcha", their site (captcha.org or something) will have links to implementations.
    or google.. "java captcha implementation" ..

  • Words have random letters bolded.

    For the last week, some sites will have random letters in bold. If I highlight the words, or scroll down then back, the letters return to normal. I have tried to reinstall Firefox multiple times, but the same problem keeps cropping up. I have also tried with add-ons disabled. It does not happen in IE.

    Try disabling graphics hardware acceleration. Since this feature was added to Firefox, it has gradually improved, but there still are a few glitches.
    You might need to restart Firefox in order for this to take effect, so save all work first (e.g., mail you are composing, online documents you're editing, etc.).
    Then perform these steps:
    *Click the orange Firefox button at the top left, then select the "Options" button, or, if there is no Firefox button at the top, go to Tools > Options.
    *In the Firefox options window click the ''Advanced'' tab, then select "General".
    *In the settings list, you should find the ''Use hardware acceleration when available'' checkbox. Uncheck this checkbox.
    *Now, restart Firefox and see if the problems persist.
    Additionally, please check for updates for your graphics driver by following the steps mentioned in the following Knowledge base articles:
    [[Troubleshoot extensions, themes and hardware acceleration issues to solve common Firefox problems]]
    [[Upgrade your graphics drivers to use hardware acceleration and WebGL]]
    Did this fix your problems? Please report back to us!

Maybe you are looking for

  • Users getting disabled during Synchronization

    Hi All, We are running Plumtree 5.0.2 in Windows Environment under Tomcat and also used Sample Application "Auth_HelloWorld-Java" as the base and modified it as per the current needs for Authentication and Synchronization. When I run the Synchronizat

  • I have photoshop on my mac book but I can not get it to update thru my creative cloud

    I have photoshop on my mac book but can not get it to update thru creative cloud installer any idea's everything else has updated but i can not get the latest version of photoshop cs6 update

  • Urgent - SLD problem

    Hi guys, I have a scenario in which i have a central SLD for developement and quality servers. I am pointing developement SLD to quality SLD . In the technical system i can see both developement and quality server   But there is no entry in software

  • Query on Correct Toplink Usage for insert/update

    Hi, I have a JSF based web application where-in my backing bean is having the Toplink generated enities as managed properties. i.e. the Toplink entity is being populated by the JSF value binding. Now when I want to insert/update this entity, what app

  • Exported images downsized

    With my last batch of photos i exported from Aperture to stock agencies, etc., they were exported at 1/2 size, i.e. in Aperture the image is 3888x2592, but exports at 1944x1296.  I have set my preferences at no limit, but does not help.  Previously,