Need to write java program to convert english to pirate talk

yeah i know its not original but i basically need java program that will translate english sentences into pirate talk using this user interface.
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;
import java.awt.*;
import javax.swing.*;
public class boy extends JFrame
JTextArea englishtxt;
JLabel head,privatetxtwords;
JButton translateengtoprivatewords;
Container c1;
public boy()
        super("HAKIMADE");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBackground(Color.white);
        setLocationRelativeTo(null);
        c1 = getContentPane();
         head = new JLabel(" English to private talk Translator");
         englishtxt = new JTextArea("Type your text here", 10,50);
         translateengtoprivatewords = new JButton("Translate");
         privatetxtwords = new JLabel();
        JPanel headlabel = new JPanel();
        headlabel.setLayout(new FlowLayout(FlowLayout.CENTER));
        headlabel.add(head);
        JPanel englishtxtpanel = new JPanel();
        englishtxtpanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,40));
        englishtxtpanel.add(englishtxt);
         JPanel panel1 = new JPanel();
         panel1.setLayout(new BorderLayout());
         panel1.add(headlabel,BorderLayout.NORTH);
         panel1.add(englishtxtpanel,BorderLayout.CENTER);
        JPanel translateengtoprivatewordspanel = new JPanel();
        translateengtoprivatewordspanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,40));
        translateengtoprivatewordspanel.add(translateengtoprivatewords);
         JPanel panel2 = new JPanel();
         panel2.setLayout(new BorderLayout());
         panel2.add(translateengtoprivatewordspanel,BorderLayout.NORTH);
         panel2.add(privatetxtwords,BorderLayout.CENTER);
         JPanel mainpanel = new JPanel();
         mainpanel.setLayout(new BorderLayout());
         mainpanel.add(panel1,BorderLayout.NORTH);
         mainpanel.add(panel2,BorderLayout.CENTER);
         c1.add(panel1, BorderLayout.NORTH);
         c1.add(panel2);
public static void main(final String args[])
        boy  mp = new boy();
         mp.setVisible(true);
}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[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 very new in java                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Garrr! Old Cap'n Nelbeard could never resist the lure of a pirate challenge.
package sandbox.swing.pirate;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class PirateTranslator implements ActionListener
   private JTextArea pirateArea;
   private JTextArea englishArea;
   private Hashtable dictionary;
   public static void main(String[] args)
      SwingUtilities.invokeLater(new Runnable(){
            public void run()
            createAndShowGUI();
   private static void createAndShowGUI()
      PirateTranslator translator = new PirateTranslator();
      translator.initDictionary();
      translator.launch();
   private void initDictionary()
      dictionary = new Hashtable();
      dictionary.put("hello", "ahoy");
      dictionary.put("hakimade", "scurvy dog");
   private 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();
      String[] englishWords = english.split(" ");
      for (String word : englishWords)
      if (dictionary.containsKey(word))
         pirateArea.append((String)dictionary.get(word));
      else
         pirateArea.append(word);
      pirateArea.append(" ");
}I couldn't be bothered to work around letter cases or punctuation as it's 5pm and my office is shutting. Time to go home and drink some <strike>beer</strike> rum.

Similar Messages

  • Need help w java program

    i have to writea java program.
    write a java program to make change when an item that costs less than a dollar is purchased and the buyer gives the seller a one dollar bill. the goal is to provide the buyer as few coins as possible in the change. the program must determine how many quarters, how many dimes, how many nickles, and how many pennies to return. the ideal program would read in the cost of the item purchased, but for now your program should just set the cost of the item to be 32 cents.
    what am i supposed to do. thank you!!

    i only have to make the first step, which is showing that the item costs 32 cents.
    so far i got this:
    public class change {
    public static void main(String[] args) {
    System.out.println("Cost = $0.32);
    however, i get this error message:
    Could not find the main class: change. Program will exit.
    Exception in thread "main"
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    i downloaded jgrasp on my computer and i got this message, this never happened with the school pc. so maybe i did sth wrong with the program or i don't have the right software on my computer.

  • Need help in java program execution...

    Hi all
    I have made a java program( JAR file) and I need to execute it from a double click...can you please tell how to do it..For normal execution i have to go to CMD prompt and write a couple of commands but i want to execute it through 1 click..
    The method which i thought was to make a batch(.bat) file and write the commands in it but its not working properly...do you have any other method or software which i can use...
    I am new to java and any help would be appreciated.

    You should avoid using a batch file since there's no explicit reason to do that.
    sachinmittal wrote:
    I have made a java program( JAR file) and I need to execute it from a double click...can you please tell how to do it.There a lot of tutorials out there. I prefer this one:
    [http://java.sun.com/docs/books/tutorial/deployment/jar/index.html]
    You should take look at the manifest section if you want to build an executable jar.

  • Need help connecting java-program to Clarion-software/database

    I have made a simple java-program which monitors control-lines in a computers com-port. Now I need to pass this information to Clarion-based software.
    I am currently writing the changes in to a file from which the clarion software will read the changes, but is there any better way to do this?

    Check out these websites:
    - http://www.softvelocity.com
    - http://en.wikipedia.org/wiki/Clarion_programming_language
    The problems is actually the fact that i don't have access to this clarion-based software or it's APIs etc.
    Message was edited by:
    RDuck

  • What do you use to write Java programs?

    Hi. Do you mind if I ask you what do you use to write your programs in Java? I am a student and we are using NetBeans IDE 3.6. I know it is a bit old but the tutor says we must stick to that one. What is best for writing Java programs?
    Thanks.

    Do you think those things will make things easier or is it more complex?If you're learning on your own, you'd better use something more up to date (most probably better interface, childhood bugs fixed, and better support on the Internet).
    If you're in a classroom, or a training room, you'd better use what the instructor tells, or at least what other students/trainees use. Easier to get help and share tips if everyone has the same setup.
    Good luck learning Java.

  • Need to write BDC program for Transaction VA01(Sales order creation)

    Dear Friends,
    I need to write a BDC program for uploading data into sap from an excel sheet file. The data contain Material Description,Customer Name,Date of Delivery,Quantity,Unit of measure etc.
    material desc customer date of delivery quantity unit of measure
    abcdf xyz ltd 24.12.2011 2 4 gm
    The transaction is VA01.How will I find the correct fields and related tables? What are the related fields needed in the transaction VA01.
    Thanking you
    Sacheen Pukhrambam
    Moderator Message: Put some self-effort before posting your question. Thread locked.
    Edited by: Suhas Saha on Nov 25, 2011 1:25 PM

    Hello,
    You could try using a BDC with VL04 but first preference would be to see if there are any BAPI functions (search for BAPI) that can do this.
    If BUS2032 doesn't have an attribute that you want (eg shipping point) then sub-delegate to ZBUS2032 and add the attribute, it's straightforward. You just have to know how to determine the value programmatically.
    regards
    Rick Bakker
    hanabi technology

  • Need help with Java programming installation question

    Sorry for my lack of knowledge about Java programming, but:....
    A while back I thought I had updated my Java Runtime Environment programming. But I now apparently have two programs installed, perhaps through my not handling the installation properly. Those are:
    J2SE Runtime Environment 5.0 update 5.0 (a 118MB file)
    and:
    Java 2 Runtime Environment, SE v 1.4.2_05 (a 108MB file)
    Do I need both of these installed? If not, which should I uninstall?
    Or, should I just leave it alone, and not worry about it?
    Yeah, I don't have much in the way of technical knowledge...
    Any help or advice would be appreciated. Thank you.
    Bob VanHorst

    Thanks for the feedback. I think I'll do just that. Once in a while I have a problem with Java not bringing up a webcam shot, but when that happens, it seems to be more website based than a general condition.

  • Need help with Java program from Yahoo

    Please excuse this novice question but I'm trying to launch "Market Tracker on Yahoo and am having problems. Yahoo says it's because I have multiple versions of Sun JVM running on my system and instructed me to do an uninstall of Jave which I did then restarted my computer. I was instructed to sign into Yahoo Finance and launch Market Tracker which detected that I needed the latest version of Sun JVM and automaticall installed it on my machine. Same problems exists. I uninstalled Java again an then did a search and found an SDK Java 40 application still on my computer. Could this be the problem? Can I remove this and what is it? Can anyone email me an answer at Bulrush2001 @ yahoo.com. Thanks in advance.

    Alas,most likely nobody here in this forum will have an answre for you.
    We're all about Sun Java Enterprise Messaging Server.
    not about JAVA, java programming, or JVM

  • Need Help On Java Programming

    1. I want to know how to write a program to design & applet GUI for a scientific calculator.
    2. How to write a program to read a text file & display line by line with numbers & search for a specific word in that file & display hoe many times that word appear in that file?

    I think u should do ur assignment by ur self !!!

  • Help needed, new to java programming

    hi,
    I have craeted a Frame with some check boxes and button called "button1".
    Can anyone tell me how can i count the number of CHECKED check boxes so that when i press the button1 in my code it should display the result as number of checked check boxes divided by total number of check boxes. It should display the result in a textfield here RESULT textfield in my code
    Thanks in advance ...i am sending the code i have written so far....
    public class Frame extends java.awt.Frame {
        /** Creates new form Frame */
        public Frame() {
            initComponents();
            setSize(600, 600);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            buttonGroup1 = new javax.swing.ButtonGroup();
            checkbox1 = new java.awt.Checkbox();
            checkbox2 = new java.awt.Checkbox();
            checkbox3 = new java.awt.Checkbox();
            button1 = new java.awt.Button();
            textField1 = new java.awt.TextField();
            setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            checkbox1.setLabel("checkbox1");
            add(checkbox1);
            checkbox1.setBounds(160, 50, 84, 20);
            checkbox2.setLabel("checkbox2");
            add(checkbox2);
            checkbox2.setBounds(160, 70, 84, 20);
            checkbox3.setLabel("checkbox3");
            add(checkbox3);
            checkbox3.setBounds(160, 90, 84, 20);
            button1.setLabel("button1");
            button1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    button1ActionPerformed(evt);
            add(button1);
            button1.setBounds(150, 180, 57, 24);
            textField1.setText("Result");
            textField1.setName("Result");
            add(textField1);
            textField1.setBounds(260, 180, 44, 20);
            pack();
        private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
            // Add your handling code here:
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new Frame().show();
        // Variables declaration - do not modify
        private java.awt.Button button1;
        private javax.swing.ButtonGroup buttonGroup1;
        private java.awt.Checkbox checkbox1;
        private java.awt.Checkbox checkbox2;
        private java.awt.Checkbox checkbox3;
        private java.awt.TextField textField1;
        // End of variables declaration
    }

    Two problems in the code you repost-ed:
    1. It lacks import statements.
    2. There is an extraneous } at the end of the button1ActionPerformed method.
    Correct them and it'll work fine. Posting the full source code:
    import java.awt.Component;
    import java.awt.Checkbox;
    public class Frame extends java.awt.Frame
         /** Creates new form Frame */
         public Frame()
              initComponents();
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always
          * regenerated by the Form Editor.
         private void initComponents()
              checkbox1 = new java.awt.Checkbox();
              checkbox2 = new java.awt.Checkbox();
              checkbox3 = new java.awt.Checkbox();
              button1 = new java.awt.Button();
              textField1 = new java.awt.TextField();
              setLayout( null );
              addWindowListener( new java.awt.event.WindowAdapter()
                   public void windowClosing( java.awt.event.WindowEvent evt )
                        exitForm( evt );
              checkbox1.setLabel( "checkbox1" );
              add( checkbox1 );
              checkbox1.setBounds( 120, 40, 84, 20 );
              checkbox2.setLabel( "checkbox2" );
              add( checkbox2 );
              checkbox2.setBounds( 120, 60, 84, 20 );
              checkbox3.setLabel( "checkbox3" );
              add( checkbox3 );
              checkbox3.setBounds( 120, 80, 84, 20 );
              button1.setLabel( "button1" );
              button1.addActionListener( new java.awt.event.ActionListener()
                   public void actionPerformed( java.awt.event.ActionEvent evt )
                        button1ActionPerformed( evt );
              add( button1 );
              button1.setBounds( 50, 170, 57, 24 );
              textField1.setText( "textField1" );
              add( textField1 );
              textField1.setBounds( 240, 170, 60, 20 );
              pack();
         private void button1ActionPerformed( java.awt.event.ActionEvent evt )
              // Add your handling code here:
              Component[] components = getComponents();
              int numOfCheckBoxes = 0;
              int numChecked = 0;
              for ( int i = 0; i < components.length; i++ )
                   if ( components[i] instanceof Checkbox )
                        numOfCheckBoxes++;
                        Checkbox checkBox = (Checkbox) components;
                        if ( checkBox.getState() )
                             numChecked++;
              double ratio = (double) numChecked / (double) numOfCheckBoxes;
              textField1.setText( Double.toString( ratio ) );
         /** Exit the Application */
         private void exitForm( java.awt.event.WindowEvent evt )
              System.exit( 0 );
         * @param args the command line arguments
         public static void main( String args[] )
              new Frame().show();
         // Variables declaration - do not modify
         private java.awt.Button button1;
         private java.awt.Checkbox checkbox1;
         private java.awt.Checkbox checkbox2;
         private java.awt.Checkbox checkbox3;
         private java.awt.TextField textField1;
         // End of variables declaration
    I can see from the code that the GUI was generated by a tool. Since you're new to Java programming, I'd recommend ditching the tool and writing everything by hand, otherwise you're not learning much. It's just like when you're learning proofs in Maths, where you start with first principles before making use of the proofs on their own.
    Also, it'll help tremendously if you could spend some time going through the Java Tutorial (http://java.sun.com/docs/books/tutorial/). It's free, and I find it very useful.
    Hth.

  • Needed to Write a program dun know how to start  Can anyone suggest

    Objective
    The student will develop classes to implement Dancing
    Turtles using the ACM graphics library.
    Special Requirement
    This assignment uses the acm.graphics package developed by the ACM
    and SIGCSE Java task Force,in particular the turtle graphics class
    GTurtle.
    Running Programs using the Graphics Library
    It turns out that it is easier to run Java Applets using
    the Graphics library that Java applications. There
    is one subtle differences in your code. There is no longer a main()
    method. Instead, your main class
    implements an instance method named run(). The other difference is
    that you choose to run the
    program as an applet. In fact, without the main method, the Run As Java Application menu option
    doesn't even show up.
    Turtle Graphics Background
    Using turtles to create graphics goes back to 1967 with the development
    of the Logo language by Wally
    Feurzeig and Seymour Papert. It uses a set of simple commands to have a
    turtle move around a screen,
    leaving a drawn path in its wake. This simple approach to creating
    graphi
    cs has been repeated in many
    different places, including the ACM graphics library. If you look at
    the GTurtle class in the ACM
    library, you see very intuitive methods like forward() and right(angle).
    Your instructor has put a copy of a simple Simple Turtle Graphics
    program on your course web page.
    The easiest way to run this program is to copy it into an eclipse class of the same name. Then choose
    Run As -> Java Applet.
    Suppose that we would like to model turtles that dance. One kind of
    turtle will move according to adance step pattern that is specified by a sequence of directions in which the turtle is to move. This type
    of turtle is a lead dancer.
    A second kind of turtle is the follower; this turtle will have a reference to
    another turtle and will mimic its moves by moving in the same direction
    on each move. You are to implement these two turtle classes and any other interfaces and classes you need to get the job done.
    TurtleMove class
    Develop a small class named TurtleMove. Each object of type turtle move
    should have two instance
    variables:
    ? a String named action that contains the action ("forward" or "right")
    that the turtle is to do.
    ? a double named arg that contains the argument (if any) for the action.
    The DancingTurtle Interface
    Develop an interface named DancingTurtle that contains declarations
    for the following two
    methods:
    public void move();
    public TurtleMove getMove();
    LeadTurtle
    Develop a class named LeadTurtle. Lead turtles extend GTurtle and
    implement DancingTurtle.
    The LeadTurtle's only constructor takes an array of TurtleMoves as its
    parameter. Each time move() is called, the next move in the array is executed. When the list is exhausted, it starts again at
    the beginning. A call to getMove() returns the next move that is to be
    executed.
    FollowerTurtle
    This type of turtle is assigned another turtle as its "leader" when it
    is constructed (this means that the
    other turtle must exist before this turtle is created). The leader is
    passed as a parameter to the
    constructor. A follower turtle's move() method calls the leader's
    getMove() method to determine
    what to do next. Note that FollowerTurtles also must implement
    getMove(), as a
    FollowerTurtle might be another turtle's leader.
    Write a separate class with a run method to test your code. Your
    instructor will run your test code, but also test your program using his own test driver.
    .

    No one is going to do your work for you. What you need to do is break it down step by step, and implement one feature at a time.
    I would start with the TurtleDancerLead and TurtleDancer, and write down what features each would need, and any common features. When you get some code written and get stuck, post what yo uhave here and ask a specific question, and someone will be gald to help.
    Quite frankly, I'm somewhat amazed at the amount of info provided to you, everything you need is there, I believe.
    ~Tim

  • Need help for Java Programming asap plzzzzzzzzzzzzz

    Here is the work: (Im writing it coz I wasn't able to attach it)
    Introduction
    In geometry, a straight line is the shortest distance between two points.
    A line may be characterised by its end points and its length.
    A line connects the points P1 and P2.
    The point P1 has coordinates {X1,Y1}.
    The point P2 has coordinates {X2,Y2}.
    The length of the line joining P1 and P2 is given by the equation:
    { (X2 - X1)2 + (Y2 - Y1)2 }1/2
    Those of you who are familiar with geometry will recognise the equation as being the well known Pythagoras equation for the hypotenuse of right angled triangles.
    Requirements
    Develop a class specification for the class Point.
    Write a short test program and test plan for this class.
    For example:
    //pointTest.java
    main(...)
    Point P1;
    P1.create(24,16); // create a point with coordinates {24,16}
    P1.display(); // display the {X,Y} coordinates of P1
    Develop a class specification for the class Line.
    Write a short test program and test plan for this class.
    For example:
    //lineTest.java
    main(...)
    Point P1 = new Point();
    P1.create(24,16); // create a point with coordinates {24,16}
    Point P2 = new Point();
    P2.create(33,42); // create a point with coordinates {33,42}
    Line L1 = new Line();
    L1.create(P1,P2); // create a line using points P1 and P2
    System.out.println( L1.length() ); // display the length of line L1
    Line L2 = new Line();
    L2.create(12,30,28,16); // create a line using coordinates {12,30}, {28,16}
    L2.display(); // display the coordinates of both points and the length of the line
    Application
    We wish to determine the length of the boundary of any regular or irregular polygon .
    The polygon may have up to 6 sides.
    The user should be prompted to enter the number of sides and the coordinates of each vertex point.
    The program should then calculate and display the total length of the boundary.
    You should write an application to implement this using your Point and Line classes.
    What I should have at the end
    The following:
    ? A listing of the files Point.java, the class test program and results.
    ? A listing of the files Line.java, the class test program and results.
    ? The application program and results.
    Note 1: All code must be written in java.

    Point P1 = new Point();
    P1.create(24,16); // create a point with coordinates {24,16}That's a terrible idea. If that was actually in your requirements, then whoever wrote it should stop teaching Java right now.
    We have constructors to initialize objects with sensible, meaningful values. Creating a new Point object without any values and then calling a "create()" method to set the values is a pretty stupid approach. Not only does it ignore the usefulness of a constructor, it also ignores the convention that methods called "create" should actually create something (and not just set values).

  • Help Needed on a java program

    I am very new to java and our teacher has given us a program
    that i am having quite a bit of trouble with. I was wondering if anyone could help me out.
    This is the program which i have bolded.
    {You will write a Java class to play the TicTacToe game. This program will have at least two data members, one for the status of the board and one to keep track of whose turn it is. All data members must be private. You will create a user interface that allows client code to play the game.
    The user interface must include:
    � Boolean xPlay(int num) which allows x to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
    � Boolean oPlay(int num) which allows o to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
    � Boolean isEmpty(int num) will check to see if the square labeled by num is empty.
    � Void display() which displays the current game status to the screen.
    � Char whoWon() which will return X, O, or C depending on the outcome of the game.
    � You must not allow the same player to play twice in a row. Should the client code attempt to, xPlay or oPlay should print an error and do nothing else.
    � Also calling whoWon when the game is not over should produce an error message and return a character other than X, O, or C.
    � Client code for the moment is up to you. Assume you have two human players that can enter the number of the square in which they want to play.
    Verifying user input WILL be done by the client code.}

    This is the program which i have bolded.Hmmm, that doesn't look like any programming language I've ever seen. I guess you have the wrong forum here, because it isn't Java.
    That looks like a natural-language programming language that directly understands a homework assignment. Either that, or you really did just post the assignment. You wouldn't have done that though, right?

  • Need help with java program

    Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item
    should display. the GUI using Java graphics classes.
    ? Add a company logo to? Post as an attachment Course Syllabus
    here is my code // created by Nicholas Baatz on July 24,2007
      import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class Inventory2
    //main method begins execution of java application
    public static void main(final String args[])
    int i; // varialbe for looping
    double total = 0; // variable for total inventory
    final int dispProd = 0; // variable for actionEvents
    // Instantiate a product object
    final ProductAdd[] nwProduct = new ProductAdd[5];
    // Instantiate objects for the array
    for (i=0; i<5; i++)
    nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
    nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
    nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
    nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
    nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
    for (i=0; i<5; i++)
    total += nwProduct.length; // calculate total inventory cost
    final JButton firstBtn = new JButton("First"); // first button
    final JButton prevBtn = new JButton("Previous"); // previous button
    final JButton nextBtn = new JButton("Next"); // next button
    final JButton lastBtn = new JButton("Last"); // last button
    final JLabel label; // logo
    final JTextArea textArea; // text area for product list
    final JPanel buttonJPanel; // panel to hold buttons
    //JLabel constructor for logo
    Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
    label = new JLabel(logo); // create logo label
    label.setToolTipText("Company Logo"); // create tooltip
    buttonJPanel = new JPanel(); // set up panel
    buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
    // add buttons to buttonPanel
    buttonJPanel.add(firstBtn);
    buttonJPanel.add(prevBtn);
    buttonJPanel.add(nextBtn);
    buttonJPanel.add(lastBtn);
    textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
    // add total inventory value to GUI
    textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
    textArea.setEditable(false); // make text uneditable in main display
    JFrame invFrame = new JFrame(); // create JFrame container
    invFrame.setLayout(new BorderLayout()); // set layout
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
    invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
    invFrame.setTitle("Office Min Inventory"); // set JFrame title
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
    //invFrame.pack();
    invFrame.setSize(400, 400); // set size of JPanel
    invFrame.setLocationRelativeTo(null); // set screem location
    invFrame.setVisible(true); // display window
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end firstBtn actionEvent
    }); // end firstBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // prevBtn.addActionListener(new ActionListener()
    // public void actionPerformed(ActionEvent ae)
    // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    // textArea.setText(nwProduct.display(dispProd)+"\n");
    // } // end prevBtn actionEvent
    // }); // end prevBtn actionListener
    } // end main
    } // end class Inventory2
    class Product
    protected String prodName; // name of product
    protected int itmNumber; // item number
    protected int units; // number of units
    protected double price; // price of each unit
    protected double value; // value of total units
    public Product(String name, int number, int unit, double each) // Constructor for class Product
    prodName = name;
    itmNumber = number;
    units = unit;
    price = each;
    } // end constructor
    public void setProdName(String name) // method to set product name
    prodName = name;
    public String getProdName() // method to get product name
    return prodName;
    public void setItmNumber(int number) // method to set item number
    itmNumber = number;
    public int getItmNumber() // method to get item number
    return itmNumber;
    public void setUnits(int unit) // method to set number of units
    units = unit;
    public int getUnits() // method to get number of units
    return units;
    public void setPrice(double each) // method to set price
    price = each;
    public double getPrice() // method to get price
    return price;
    public double calcValue() // method to set value
    return units * price;
    } // end class Product
    class ProductAdd extends Product
    private String feature; // variable for added feature
    public ProductAdd(String name, int number, int unit, double each, String addFeat)
    // call to superclass Product constructor
    super(name, number, unit, each);
    feature = addFeat;
    }// end constructor
    public void setFeature(String addFeat) // method to set added feature
    feature = addFeat;
    public String getFeature() // method to get added feature
    return feature;
    public double calcValueRstk() // method to set value and add restock fee
    return units * price * 0.05;
    public String toString()
    return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
    getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAddI can not get all the buttons to work and do not know why can someone help me

    You have to have your code formatted correctly to begin with before you add the code tags. All your current code is left-justified and is not indented correctly.
    I only see that you've added an actionlistener to the "first" button.
    I recommend that you:
    1) again, do this first in a nonGUI class, then use this nonGUI class in your GUI class.
    2) Have a integer variable that holds the location of the current Product that your application is pointing to.
    3) Have a method called getProduct(int index) that returns the product that is at the location specified by the index in your array / arraylist / or whatever collection that you are using.
    4) Have your first button set index to 0 and then call getProduct(index).
    5) Have your last button set your index to the last product in your collection (i.e.: index = productCollection.length - 1 if this is an array), and then call getProduct(index).
    5) Have your next button increment your index up to the maximum allowed and then call getProduct(index). If it's an array it goes up to the array length - 1.
    6) If you want the next button to cause the index to roll over to the first, when you are at the last then then increment the index and mod it ("%" operator) by the length of the array...

  • Need help with Java Programming

    Hello All,
    I dont know how to save all the lines separatly and then work with the numbers?
    Example TxtIn:
    2 5
    0 9 2 3 4 // I dont know how many lines will appear, and dont know how many numbers in a line
    1 2 3 9
    1 5 4
    2 0 0 5 6
    2 5 1 9
    4 6 1 5
    4 9 1 8
    9 1 4 8
    9 5 0
    Example TxtOut:
    1 9 4 0
    I would really appreciate your help in this.
    In my code, i only past one time in the text file, and clear the numbers of the list, but i need to make more check =S
    Here is the code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    * @author Antonio
    public class web {
        /** Creates a new instance of Main */
         * @param args the command line arguments
        public static void main(String[] args) throws FileNotFoundException {
            int contador;
            ArrayList<Integer> lista = new ArrayList<Integer>();
            Scanner scn = new Scanner(new File("in.txt"));
            try {
            PrintWriter fileOut = new PrintWriter(new FileWriter("out.txt"));
            int ciudades = scn.nextInt();
            int aerolineas = scn.nextInt();
            int ciudadabuscar = scn.nextInt();
            int aerolinea = scn.nextInt();
            int bandera=0;
            while (scn.hasNextLine()){
                    String cad = scn.nextLine();
                    StringTokenizer st = new StringTokenizer(cad," ");
             while (st.hasMoreTokens())
                    String t = st.nextToken();
                    lista.add ( Integer.parseInt(t) );
               int a[]= new int[lista.size()];
               for (int x=0; x<lista.size(); x++)
                            a[x] = lista.get(x);
                          for (int x=0; x<lista.size(); x++)
                   for (x=1;x<lista.size();x++){
                            if (ciudadabuscar == a[0] && aerolinea == a[1])//tenia x=1
                                for (x=2;x<lista.size();x++)
                                { fileOut.printf("%d ",a[x]);
                                  ciudadabuscar= a[2];
                                  bandera = 1;}
                         lista.clear();
            if(bandera==0){
            fileOut.println("No hay destinos posibles por esta línea");
            fileOut.close();
            }catch(FileNotFoundException ex){}catch(IOException ex){}
    }

    #1 Solution is the same as i am working but...if i found AND another pair needs tobe searched...i dont know how to start again with step 1...
    i onli continues reading..that is why i am never show
    2 5//i am reading the file looking for 2 and 5
    0 9 2 3 4
    1 2 3 9
    1 5 4 // I NEVER show the number 4....
    2 0 0 5 6
    2 5 1 9 // here i found them...and now i have to look in the file 1 5 and 9 5 (but 1 5 are before this..so i can never found them)
    4 6 1 5
    4 9 1 8
    9 1 4 8
    9 5 0 // here i found 9 5
    Correct OutTxt: 1 9 4 0
    My OutTxt: 1 9 0...Never show the number 4, because i dont know how to start again...
    thank u
    Edited by: Ing_Balderas on Dec 11, 2009 2:25 PM

Maybe you are looking for

  • How do I hide a pulldown menu if one of it's values has been selected but not others?

    Through searching this forum, I've been able to figure out how to hide pull downs and fields that only have numeric info in them. I.e if the user selects. or if the pulldown value is zero. The item does not show or print on the form.  What I cannot f

  • Connecting AT200 to TV

    Basically I bought a mini HDMI to normal sized for my celcus TV, I'm wondering if I have to do anything special asit won't show on my TV screen, if anyone could help I'd be extremely grateful, even to point me in the right direction if the lead I hav

  • Ibook 500mhz AV cable its compatible with the iPod AV cable?

    Last Sunday i've found an old cable from my old ibook 500mhz: http://www.mac-pro.com/s.nl/sc.2/category.114/it.A/id.1383/.f Do you think it will be compatible with the ipod video that im waiting? (yes, because im from portugal and need to wait a lot

  • Is it possible to have the result from webservices with oracle8i

    hi, i call webservices MS .net with package utl_http under oracle 8i. exemple: DECLARE x utl_http.html_pieces; msg varchar2(12); BEGIN x := utl_http.request_pieces('http://localhost/ServiceNotification/Notification.asmx/NotifT?messagetmp=' || msg); E

  • SWIFT Receiver channel error

    Hi, I have configured my Fileact sender channel  as described in the "SAP Integration Package for SWIFT". But i get this error in the channel monitor. 1) Adapter Framework caught exception: java.lang.NullPointerException 2) Delivering the message to