Ignoring words if not contained in array.

Hi guys. Bit of a problem from me again. This time its not homework cos its not wednesday :wink: Its an exercise i found on the net :stuck_out_tongue:

But what I’m wondering is, how do i get a program to ignore a word(i.e String) if its not contained in an array.

Here’s what I’m working on:

public class PirateTranslater
{
	static String TranslateToPirate(String userWord)
	{

		String translatedForBlackBeard = "";

		String space = " ";

		String [] pirateVocabulary = {"ahoy",  "yo-ho-ho", "avast", "arrr", "me", "me bucko", "matey", "proud beauty", "comely wench", "scurvy dog", "whar", "be", "th'", "ye", "be tellin'", "be knowin'", "how many leagues", "barnacle-covered", "comely", "grog-filled", "broadside", "head", "galley", "fleabag inn", "Skull & Skuppers", "buried treasure"};

		String [] userText = {"hello", "hi",  "pardon me", "excuse me", "my", "friend", "sir", "madam", "miss", "stranger", "where", "is", "the", "you", "tell", "know", "how far", "old", "attractive", "happy", "nearby", "restroom", "restaurant", "hotel", "pub", "bank"};

			for(int i = 0; i < userText.length; i++)
			{

				if(userWord.equals(userText[i]))
				{
					translatedForBlackBeard = pirateVocabulary[i];	
				
				}
				else
				{
					return userWord ;
				}
			}

			return translatedForBlackBeard;
		
	}

	public static void main(String [] args)
	{
		System.out.println("Say somethin' to ol' BlackBeard!");

		String word = Console.readToken();

		while(word != null)
		{

			String convertedWord = TranslateToPirate(word);

			// deal with the word
			System.out.print(convertedWord + " ");

			//read in the next word
			word = Console.readToken();		
		}
	}
}

Here’s the problem. If i remove the else statement in the method, it prints out all the words that can be translated(i.e those contained in userText) but doesn’t print the ones that aren’t contained in the method, i.e such as ‘there’ and ‘could’. But if i do include the else staement, it just returns the original string. So any thoughts from you guys??

By the way. I’m using IO redirection for it, and here’s the input in a .txt file:

hello there sir
could you tell me where is the nearest restaurant

Thats my input!

And again, I stress its NOT homework, I’m just trying to build my skills!

And I appreciate everything you guys do for me!

Thx

Hauk

If I understand your problem, you want to “tokenize” a string. (i.e. Convert a string of text into an array of strings that can be processed.) Look up “java.util.StringTokenizer” as well as “java.lang.String.split()”. Between the two of those you should be able to figure out a solution. :slight_smile:

hmm, I’ll give it a look up and post back here. And I remember you from my days of lurking here ;D

Hauk

Actually now that I think of it, I think you misunderstood me. It doesn’t read in the entire sentence as a string, it reads in each individual word and treats it as a string. Sorry if i wasn’t clear enough!

Any other ideas now that i’ve cleared that up?

Thanks jbanes!

Hauk

What about ArrayLists?


String list[];
ArrayList<String> userText = new ArrayList<String>();
ArrayList<String> pirateVocabulary = new ArrayList<String>();

list = new String[] {"hello", "hi",  "pardon me", "excuse me", "my", "friend", "sir", "madam", "miss", "stranger", "where", "is", "the", "you", "tell", "know", "how far", "old", "attractive", "happy", "nearby", "restroom", "restaurant", "hotel", "pub", "bank"};
for(int i = 0; i < list.length; i++)
{
	userText.add(list[i]);
}

list = new String[] {"ahoy",  "yo-ho-ho", "avast", "arrr", "me", "me bucko", "matey", "proud beauty", "comely wench", "scurvy dog", "whar", "be", "th'", "ye", "be tellin'", "be knowin'", "how many leagues", "barnacle-covered", "comely", "grog-filled", "broadside", "head", "galley", "fleabag inn", "Skull & Skuppers", "buried treasure"};
for(int i = 0; i < list.length; i++)
{
	pirateVocabulary.add(list[i]);
}

System.out.println(userText.indexOf(testString) > 0 ? pirateVocabulary.get(userText.indexOf(testString)) : testString);

That last line says if the index of the testString is not negative, print out the corresponding word from the PirateVocabulary, or else return the original string

I see what you mean there, but is there a way of making it into simpler code? Without arrayLists? I really don’t want to jump in the deep end if you get my meaning :-\

Hauk

Inside your for loop you check whether the userWord is equal to the current indexed element inside userText. Unfortunatly the loop does not stop, when the correct translation is found, so in the next iteration, this check fails and returns the original word immediately (although there is a correct translation in translatedForBlackBeard).

In my eyes the ArrayList solution is much simpler as your code :stuck_out_tongue:

However I would suggest to use a HashMap for this:


public class PirateTranslator
{
	private static HashMap translations;
	static
	{
		translations= new HashMap();
		translations.put("hello","ahoy");
		translations.put("hi","yo-ho-ho");
		translations.put("pardon me","avast");
		translations.put("excuse me","arrr");
		translations.put("my","me");
		translations.put("friend","me bucko");
		translations.put("sir","matey");
		translations.put("madam","proud beauty");
		translations.put("miss","comely wench");
		translations.put("stranger","scurvy dog");
		translations.put("where","whar");
		translations.put("is","be");
		translations.put("the","th'");
		translations.put("you","ye");
		translations.put("tell","be tellin'");
		translations.put("know","be knowin'");
		translations.put("how far","how many leagues");
		translations.put("old","barnacle-covered");
		translations.put("attractive","comely");
		translations.put("happy","grog-filled");
		translations.put("nearby","broadside");
		translations.put("restroom","head");
		translations.put("restaurant","galley");
		translations.put("hotel","fleabag inn");
		translations.put("pub","Skull & Skuppers");
		translations.put("bank","buried treasure");
	}

	static String TranslateToPirate(String userWord)
	{
		// Is there a translation? then return it
		if(translations.containsKey(userWord)) return (String)translations.get(userWord);
		// Return the original word as fallback
		return userWord;
	}
}

One note: the translation of “pardon me” and “excuse me” will not work, if you feed single words to the method, so you might want to create a line translater, which might be challenging :o
Another note: don’t use upper case names for methods/functions in java, they are considered to be reserved for classes only :wink:

[quote=“Hauk,post:6,topic:25464”]
Sorry, I misunderstood what you needed. You’ll forgive me if I say so, but your problem is so simple that it didn’t even occur to me what you were asking. Let’s try this again, shall we?

So your problem is that this code returns the original text:

static String TranslateToPirate(String userWord)
{
  String translatedForBlackBeard = "";

  String space = " ";

  String [] pirateVocabulary = {"ahoy",  "yo-ho-ho", "avast", "arrr", "me", "me bucko", "matey", "proud beauty", "comely wench", "scurvy dog", "whar", "be", "th'", "ye", "be tellin'", "be knowin'", "how many leagues", "barnacle-covered", "comely", "grog-filled", "broadside", "head", "galley", "fleabag inn", "Skull & Skuppers", "buried treasure"};

  String [] userText = {"hello", "hi",  "pardon me", "excuse me", "my", "friend", "sir", "madam", "miss", "stranger", "where", "is", "the", "you", "tell", "know", "how far", "old", "attractive", "happy", "nearby", "restroom", "restaurant", "hotel", "pub", "bank"};

  for(int i = 0; i < userText.length; i++)
  {
    if(userWord.equals(userText[i]))
    {
      translatedForBlackBeard = pirateVocabulary[i];
    }
    else
    {
      return userWord ;
    }
  }

  return translatedForBlackBeard;
}

But if you remove the “else { return userWord; }” it returns only Pirate speak, right?

The answer is simple. Set “translateForBlackBeard” to equal “userWord” before you begin looping, then delete the “else” statement.

Consider the following code:

private String[] ENGLISH = {"hello", "goodbye"};
private String[] SPANISH = {"hola", "adios"};

public String translate(String word)
{
    return word;
}

What does it do? Does it change the word passed in at all?

Now consider this version:

private String[] ENGLISH = {"hello", "goodbye"};
private String[] SPANISH = {"hola", "adios"};

public String translate(String word)
{
    for(int i=0; i<ENGLISH.length; i++)
    {
        if(word.equalsIgnoreCase(ENGLISH[i])) return SPANISH[i];
    }

    return word;
}

Does this version change the word? What happens if the word is not in the dictionary? Does it continue testing words after it finds a match?

As for the ArrayLists, don’t fear them. They are extremely powerful and can help you a great deal. You would be wise to learn them. :slight_smile:

I could kiss you!!!

Thanks it works great!

You rock man! This place has never failed me EVER!

A very happy,

Hauk ;D