# need to write java program to convert english to pirate talk



## devlin (Feb 22, 2005)

yeah i know its not original but i basically need java program that will translate english sentences into pirate talk. here is a basic idea of what i need in javascript:

```
<script LANGUAGE="JavaScript">
    PHRASES = [["hello", "ahoy"], ["hi", "yo-ho-ho"], ["pardon me", "avast"], 
               ["excuse me", "arrr"], ["yes", "aye"],
               ["my", "me"], ["friend", "me bucko"], ["sir", "matey"], 
               ["madam", "proud beauty"], ["miss", "comely wench"], 
               ["stranger", "scurvy dog"], ["officer", "foul blaggart"], 
               ["where", "whar"], ["is", "be"], ["are", "be"], ["am", "be"], 
               ["the", "th'"], ["you", "ye"], ["your", "yer"],
               ["tell", "be tellin'"], ["know", "be knowin'"],
               ["how far", "how many leagues"], ["old", "barnacle-covered"],
               ["attractive", "comely"], ["happy", "grog-filled"], ["quickly", "smartly"],
               ["nearby", "broadside"], ["restroom", "head"], ["restaurant", "galley"],
               ["hotel", "fleabag inn"], ["pub", "Skull & Scuppers"], ["mall", "market"],
               ["bank", "buried treasure"], ["die", "visit Davey Jones' Locker"],
               ["died", "visited Davey Jones' Locker"], ["kill", "keel-haul"],
               ["killed", "keel-hauled"], ["sleep", "take a caulk"],
               ["stupid", "addled"], ["after", "aft"], ["stop", "belay"],
               ["nonsense", "bilge"], ["officer", "bosun"], ["ocean", "briny deep"],
               ["song", "shanty"], ["money", "doubloons"], ["food", "grub"],
               ["nose", "prow"], ["leave", "weigh anchor"], ["cheat", "hornswaggle"],
               ["forward", "fore"], ["child", "sprog"], ["children", "sprogs"],
               ["sailor", "swab"], ["lean", "careen"], ["find", "come across"],
               ["mother", "dear ol' mum, bless her black soul"],
               ["drink", "barrel o' rum"], ["of", "o'"]
              ];
 
               
    function Capitalize(str)
    // Returns: a copy of str with the first letter capitalized
    {
        return str.charAt(0).toUpperCase() + str.substring(1);
    }
        
    function Translate(text)
    // Returns: a copy of text with English phrases replaced by piratey equivalemts 
    {
        for (var i = 0; i < PHRASES.length; i++) {
            var toReplace = new RegExp("\\b"+PHRASES[i][0]+"\\b", "i");
            
            var index = text.search(toReplace);
            while (index != -1) {
               if (text.charAt(index) >= "A" && text.charAt(index) <= "Z") {
                   text = text.replace(toReplace, Capitalize(PHRASES[i][1]));
               } 
               else {
                   text = text.replace(toReplace, PHRASES[i][1]);
               }
               index = text.search(toReplace);
            }
        }
 
        return text;
    }
  </script>
```
i need help quick if anyone has already done this or can map out basic idea. im ok in java but not great


----------



## wookie2u (May 6, 2007)

This is a simple "generic translator".

I didn't implement the Capitalize, coz I don't know how to make a java regex case-insensitive, and I'm to lazy to research it tonight.


```
package forums;

//references:
//http://forums.techguy.org/development/570048-need-write-java-program-convert.html
//http://www.wellho.net/resources/ex.php4?item=j714/Hmap.java

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;

public class Translate {

  public static void main(String [] args) throws IOException {
    if (args.length != 2) {
      System.err.println("usage: Translate wordmapfile textfile");
      System.exit(1);
    }
    try {
      HashMap words = ReadHashMapFromFile(args[0]);
      System.out.println(ProcessFile(words, args[1]));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  //----------------------------------------------------------------------------
  // static helper methods
  //----------------------------------------------------------------------------

  /**
   * Reads a file into a HashMap. The file should contain lines of the format 
   *    "key\tvalue\n"
   * @returns a hashmap of the given file
   */
  @SuppressWarnings("unchecked")
  private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    HashMap map = null;
    try {
      in = new BufferedReader(new FileReader(filename));
      String line;
      map = new HashMap();
      while ((line = in.readLine()) != null) {
        String[] fields = line.split("\\t", 2);
        if (fields.length != 2) continue; //just ignore "invalid" lines
        map.put(fields[0], fields[1]);
      }
    } finally {
      if(in!=null) in.close(); //may throw IOException
    }
    return(map); //returning a reference to local variable is safe in java (unlike C/C++)
  }

  /**
   * Process the given file
   * @returns String contains the whole file.
   */
  private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    StringBuffer out = null;
    try {
      in = new BufferedReader(new FileReader(filename));
      out = new StringBuffer();
      String line = null;
      while( (line=in.readLine()) != null ) {
        out.append(SearchAndReplaceWordsInText(words, line)+"\n");
      }
    } finally {
      if(in!=null) in.close(); //may throw IOException
    }
    return out.toString();
  }

  /**
   * Replaces all occurrences in text of each key in words with it's value.
   * @returns String
   */
  private static String SearchAndReplaceWordsInText(Map words, String text) {
    Iterator it = words.keySet().iterator();
    while( it.hasNext() ) {
      String key = (String)it.next();
      text = text.replaceAll("\\b"+key+"\\b", (String)words.get(key));
    }
    return text;
  }

  /**
   * @returns: s with the first letter capitalized
   */
  String capitalize(String s)
  {
    return s.substring(0,0).toUpperCase() + s.substring(1);
  }

}
```
... here's the head of my pirate_words_map.txt

```
hello	ahoy
hi	yo-ho-ho
pardon me	avast
excuse me	arrr
yes	aye
my	me
friend	me bucko
sir	matey
madam	proud beauty
miss	comely wench
stranger	scurvy dog
officer	foul blaggart
where	whar
is	be
are	be
am	be
the	th'
you	ye
your	yer
tell	be tellin'
```
and my pirate_text.txt:

```
Hello sir, 
Pardon me, but I twas nearby, in the restroom at the pub, over on circular quay
there, and excuse me sir, but I couldn't help but overhear you tell the fine 
officer of your mother killing the stranger, yes that stupid bligter with a sheep 
under his arm, in a fit pique of course, sir. Was that wise sir?
```
Good luck finishing it off. You might want to look at the "Special constructs" in Pattern API doco at: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html

Keith.


----------



## devlin (Feb 22, 2005)

i take it under your comment reads file into hashmap you replace filename with actual name of the text file and where it says process the given file i replace filename with the file name of the text i want translated. i did that and it compiles but no output is given. what am i missing?

also how hard would it be to change this to an applet so there is a field for input, field for output and translate button?


----------



## wookie2u (May 6, 2007)

devlin,

put all 3 files in a directory, then:
javac -cp . Translate.java
java -cp . Translate pirate_words_map.txt pirate_text.txt
--> You should see some pirate speak. Something about murderous mothers if I recall.

How to stick it in an applet? I Dunno. I HATE applets. THIN client. Not "thin client" with full cream controls.

Personally, I'd stick in a bean (or a servlet) and give it a JSP frontend. Much cleaner.

Keith.


----------



## rushtopulkit (Jun 16, 2008)

i need to convert a simple java program into binary code ... so that the new code is not visible to others .. not even the source code can be known about the code .. 
what is the code for a program like

public class NewClass 
{ 
public static void main (String args[])
{

System.out.println("hi");

}
}


----------



## Chicon (Jul 29, 2004)

Hi rushtopulkit,

Welcome to TSG ! 

You may need to compile your Java coding with an obfuscator . Obfuscators are used to make decompilation or reverse engineering the more difficult possible with the lesser loss of performance.
Unfortunately, the best ones are generally very expensive !


----------



## rushtopulkit (Jun 16, 2008)

how to convert the code of a jsp program ... so that the code is not known by others .. even by using right click to view the source code in the browser .. i.e how to convert the jsp code so that it can only be viewed by the programmer and not by the users .. !


----------



## Chicon (Jul 29, 2004)

Unfortunately, you can't prevent the user to look at the source of your JSP as JSP's are similar to HTML pages.
BTW, with your JSP, you may redirect each user's response to servlets. It's more secure as the coding of servlets is inaccessible.


----------



## rushtopulkit (Jun 16, 2008)

i have been asked to convert a jsp code into some binary format or something .. so that it cannot be visible to others using the view source code command .. how do i do so ??


----------



## Chicon (Jul 29, 2004)

It looks like the person who told you so doesn't know how Web browsers work and what is a JSP.
I repeat you can't convert your JSP coding into some binary because the users' browser won't be able to render it properly.


----------



## rushtopulkit (Jun 16, 2008)

when we view the source code of a mail site .. we can see that the source code is in a binary form ... how do i convert my jsp code in that format .. 
urgent !!​


----------



## Chicon (Jul 29, 2004)

The pseudo binary code you see on the source of a Web page represents encrypted data.
The encryption is made dynamically by an application that runs on a server.
In your case, as you're using JSP's, only a Java servlet can do the job as servlets are able to build or complete Web documents on the fly and to treat HTTP requests and responses.


----------



## rushtopulkit (Jun 16, 2008)

the guy now says that .. when u use "view source code"
... the matter should not come at all .. i mean only body and no text .. he says its programming ... plz help !!
the source code is not encrypted instead it gets hidden .. i dunno how it can be done .. he says its easy ... !!
plz help Chicon !


----------



## rushtopulkit (Jun 16, 2008)

the problem is .. i need to program my .jsp file in such a way that while viewing the source code ... i see only spaces .. i.e. all the codes are converted into spaces ...all the code is converted into space n while viewing the source code only spaces are visible .. !!
urgent !


----------



## Chicon (Jul 29, 2004)

I'm assuming you're talking about hiding your Javascript coding in your JSP :
- in the directory of your web application, there must be a *WEB-INF* directory;
- there you create a directory you call, for example, *scripts*;
- in that new directory, you create a file that will contain your Javascript coding, you call the file *myscript.js*

In your the header part of your JSP, you add the following tag :

The script won't be visible in the user's browser.


----------



## rushtopulkit (Jun 16, 2008)

couldnt do it ... may be i got tangled .. plz elaborate .. 
if possible try it with .jsp instead of .js
i m not aware of .js files


u have been a great help ... thanks loads in advance .. 
but please help me out !


----------



## Chicon (Jul 29, 2004)

Seemingly, we are not working on the same wave length !

- JSP means JavaServer Page (file format .jsp) : it is a 'tailored' HTML document with specific tags. Those extra tags enclose some Java statements that are executed on the web server side. On the client side, JSP is only a HTML document.
There are a lot of talkative examples on the following page :
https://gupea.ub.gu.se/examples/jsp/
For each example, you may display the source server side, execute the JSP and view in your browser what source it has generated. You'll notice that you won't find any piece of Java coding.

- Javascript is something completely different. A Javascript program is executed only by the client browser. Javascript programs are generally stored in file with .js extension.


----------



## rushtopulkit (Jun 16, 2008)

i can still view the code ... it dint work .. help me out .. 
did u try it ?
i use net beans .. n the code was visible .. i tried everything !


----------



## Chicon (Jul 29, 2004)

Hi rushtopulkit,

There's no need to use NetBeans to view the examples. Only a web browser is sufficient.
If you view the source code of *Date* in the *JSP 1.2 Examples*, it is the code of the JSP server side.
On the client browser, you should view the following coding with your source viewer when you execute *Date*:


> Day of month: is 18
> Year: is 2008
> Month: is June
> Time: is 15:48:26
> ...


It's normal :
- the HTML tags are still needed in order to display the results in the client browser
- the JSP tags are not showing any more as they only work on the server.


----------



## rushtopulkit (Jun 16, 2008)

thanks a lot Chicon ... 
but i guess this is not what he wants ... i ll show it to him today n then lets see 
anyway thanks loads for all wat u did !!


----------



## Chicon (Jul 29, 2004)

You're welcome !


----------



## rushtopulkit (Jun 16, 2008)

hi chicon !
when i run the code thru Netbeans .. it does not work .. wat shud i do to make it work in Netbeans .. 
it works on the browser though but i need to show it thru Netbeans !


----------



## Chicon (Jul 29, 2004)

The code won't run alone like a simple console program. You've have to build a web application with NetBeans.
Also, the *Date* JSP I referred to is invoking an _EJB_ (Enterprise Java Bean) called _dates.JspCalendar_. EJB's are modules running on web server.
To explain how to build such application is not an easy task.


----------

