|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
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! |
|
#2
|
||||
|
||||
|
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.)
__________________
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 Short • Understanding the C/C++ Preprocessor Taming Python • A 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. |
|
#3
|
|||
|
|||
|
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. |
|
#4
|
|||||
|
|||||
|
Here you go. Since it's homework you get to finish it =)
java Code:
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. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Java Help > Multidimensional Array/JavaScript Translation help |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|