Java Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesJava Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old May 3rd, 2008, 08:12 PM
cynosureepr cynosureepr is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2008
Posts: 2 cynosureepr User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 20 m 58 sec
Reputation Power: 0
Multidimensional Array/JavaScript Translation help

Hey =D

So.. I had a java assignment. The goal was to construct a java applet that translated whatever the user input to "pirate talk". wooh. In the class, we haven't done anything regarding multidimensional arrays.. or really gathering information from arrays at all.

He gave us this javascript code; our goal was to translate it to java so that it worked in our applet.
Code:
 PHRASES = [["hello", "ahoy"], ["hi", "yo-ho-ho"], ["pardon me", "avast"],
               ["excuse me", "arrr"],
               ["my", "me"], ["friend", "me bucko"], ["sir", "matey"],
               ["madam", "proud beauty"], ["miss", "comely wench"],
               ["stranger", "scurvy dog"], ["officer", "foul blaggart"],
               ["where", "whar"], ["is", "be"], ["the", "th'"], ["you", "ye"],
               ["tell", "be tellin'"], ["know", "be knowin'"],
               ["how far", "how many leagues"], ["old", "barnacle-covered"],
               ["attractive", "comely"], ["happy", "grog-filled"],
               ["nearby", "broadside"], ["restroom", "head"], ["restaurant", "galley"],
               ["hotel", "fleabag inn"], ["pub", "Skull & Scuppers"],
               ["bank", "buried treasure"]
              ];
               
    function Translate(text)
    // Returns: a copy of text with English phrases replaced by piratey equivalents
    {
        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) {
               text = text.replace(toReplace, PHRASES[i][1]);
               index = text.search(toReplace);
            }
        }
        return text;
    }



So, I did all to my ability.. lol;
I just can't figure out how to get what's in that for loop to work to save my neck.
Can anyone help me out here?


This is what I currently have:
(the for loop that doesn't compile is under the "actionPerformed" method)
Code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

 
public class PirateTranslator3 implements ActionListener
{
 
   private JTextArea pirateArea;
   private JTextArea englishArea;

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

      translator.launch();
   }
   
   

   
   public void launch()
   {
      JFrame applicationFrame = new JFrame("Talk like a Pirate!");
      applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      applicationFrame.getContentPane().setLayout(new BorderLayout());
      
      englishArea = new JTextArea();
      englishArea.setPreferredSize(new Dimension(200,200));
      applicationFrame.getContentPane().add(englishArea, BorderLayout.NORTH);
      
      JButton button = new JButton("Translate");
      button.addActionListener(this);
      applicationFrame.getContentPane().add(button, BorderLayout.CENTER);
      
      pirateArea = new JTextArea();
      pirateArea.setPreferredSize(new Dimension(200,200));
      applicationFrame.getContentPane().add(pirateArea, BorderLayout.SOUTH);
      
      applicationFrame.setSize(600,600);
      applicationFrame.setVisible(true);
   }
 
   public void actionPerformed(ActionEvent e)
   {


	
	String english = englishArea.getText();
	


	for (int i = 0; i < PHRASES.length; i++ )
	{
		
		String toReplace = new RegExp("\\b"+PHRASES[i][0]+"\\b", "i");
		String index = english.search(toReplace);

	while (index != -1){
		if (english.charAt(index) >= "A" && english.charAt(index) <= "Z")
		{	english = english.replace(toReplace, Capitalize(PHRASES[i][1])); }
		else
		{	english = english.replace(toReplace, PHRASES[i][1]); }

		index = english.search(toReplace);
	}
	}



	










   }
     public static void main(String[] args)
   {
      SwingUtilities.invokeLater(new Runnable(){
 
	       public void run()
	       {
		  createAndShowGUI();
	       }
 
	    });
   }
   
}


Thanks a bunch!

Reply With Quote
  #2  
Old May 4th, 2008, 01:36 PM
Schol-R-LEA's Avatar
Schol-R-LEA Schol-R-LEA is offline
Commie Mutant Traitor
Dev Shed Beginner (1000 - 1499 posts)
 
Join Date: Jun 2004
Location: The People's Republic of Berkeley
Posts: 1,157 Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level)Schol-R-LEA User rank is Colonel (50000 - 60000 Reputation Level) 
Time spent in forums: 3 Weeks 6 Days 14 h 44 m 6 sec
Reputation Power: 539
The primary issue is that Java handles regular expressions very differently from JavaScript. There are many tutorials on Java pattern matching around which might help.

If I were designing this myself, I probably would use a HashMap rather than pattern matching. The 'patterns' in question are all simple phrases, so looking up the words in a table would be a lot simpler; the only place where this might fall down is with "how far", which you would have to handle as an exceptional instance. There are some trade-offs in it, though, and the regex approach is more flexible and a little easier to set up. Also, it is likely that your professor specifically assigned this as a regular expressions problem, though if that were the case I would have expected that you would have gotten the basic documentation on java.util.regex when it was assigned.

While it isn't a big deal in this case, I usually would recommend separating the implementation of the translator into another utility method, one taking a String and returning another String, rather than having it all wrapped up in the guts of the user interface. With this program, the only UI aspect is that it runs directly from an event, so it isn't really necessary, but you may want to do it anyway as a matter of general principle. Separating implementation and presentation is a good habit to get into, as it can simplify a lot of things that way, and make programs much easier to debug. In a more complicated example, you would usually want to write a separate class for the program logic, and test that class in a shell or console before building the GUI version; that would be rather excessive for this project, but it is something to keep in mind for the future, and I'm sure (er, let me make that, 'I hope') your instructor will discuss that later.

As a minor point, I'd recommend being more consistent with your brace style; you seem to doing things a bit haphazardly, which is a bad habit. In general, which brace style you use isn't as important as sticking to the same style throughout a given program; however, in Java, there is a standard style guide, and while there's no rule saying you can't use a different style, using the standard style will generally go over better with other Java coders. (personally, I use the Java standard for Java, and Allman style for C and C++, to make them easier to differentiate when I'm working on mutiple projects.)
Comments on this post
Joseph Taylor agrees!
__________________
Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
#define KINSEY (rand() % 7) λ Scheme is the Red Pill
Scheme in ShortUnderstanding the C/C++ Preprocessor
Taming PythonA Highly Opinionated Review of Programming Languages for the Novice, v1.1

FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov

Last edited by Schol-R-LEA : May 4th, 2008 at 01:47 PM.

Reply With Quote
  #3  
Old May 4th, 2008, 02:53 PM
cynosureepr cynosureepr is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2008
Posts: 2 cynosureepr User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 20 m 58 sec
Reputation Power: 0
Thanks! =D

Yea, I know how to do this project fairly well with a HashMap and a dictionary method and just using the 'put' thing to get them all in there; but the instructions were to take that code from javascript and translate it so that it works in java. =(

He didn't give us that link to the java sun regular expressions stuff.. thanks a bunch =D

The teacher always complains about my braces.. haha;
I honestly start off okay sometimes; but then stuff usually gets complicated and I'm adding and deleting randomly.. and by time I'm done it's like a war zone!

Thanks again for the help!
I'm gonna read up on the regular expressions and see if I can't figure this out.

Reply With Quote
  #4  
Old May 4th, 2008, 03:01 PM
tagmanadvance's Avatar
tagmanadvance tagmanadvance is offline
Kage Bunshin
Dev Shed Novice (500 - 999 posts)
 
Join Date: Aug 2005
Location: The Seven Seas Of Rhye
Posts: 771 tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level)tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level)tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level)tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level)tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level)tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level)tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level)tagmanadvance User rank is First Lieutenant (10000 - 20000 Reputation Level) 
Time spent in forums: 1 Week 5 Days 9 h 53 m 35 sec
Reputation Power: 185
Send a message via AIM to tagmanadvance Send a message via Yahoo to tagmanadvance Send a message via XFire to tagmanadvance
Here you go. Since it's homework you get to finish it =)
java Code:
Original - java Code
  1. english = english.toLowerCase();
  2. for (int i = 0; i < PHRASES.length; i++ ) {
  3.     String[] arr = PHRASES[i]; //cleaner code
  4.     //make sure arr length is 2, otherwise throw an error or continue
  5.     String englishSpeak = arr[0].toLowerCase(); //cleaner code
  6.     String pirateSpeak = arr[1].toLowerCase();
  7.     //take a look at <String>.replaceAll(<String>, <String>) for the last part
  8. }

EDIT: Just a note, most IDEs have a build in format function. You might consider loading your code into Eclipse and running the formatter before submitting it to your teacher.
__________________
"Java makes impossible things possible, but makes easy things difficult." - Somebody

Last edited by tagmanadvance : May 4th, 2008 at 03:06 PM.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesJava Help > Multidimensional Array/JavaScript Translation help


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump


Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway