Need guidance with small program... Beginner Java Programming

Hey guys im new to Java... Im currently a high school student and we've been learning java for a while now.
I am currently doing an out of class assignment meaning im doing it for my own benefit since programming is my future job and passion and love, haha.
I recently bought the Head First Java 2nd edition and need to do this following program:
Expected output:
%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10
My following code:
public class Echo
int count = 0;
void hello(){
System.out.println("helloooo... ");
public class EchoTestDrive
public static void main(String [] args){
Echo e1 = new Echo();
Echo e2 = new Echo();
int x = 0;
while( x < 4 ){    
/** We want this to be 4 so it loops around 4times to get (hello... ) x 4 ? - in the out put? */
e1.hello();
e1 = e2;
if( x==4){
e2.count = e2.count + e1.count;
x = x + 1;
System.out.println(e2.count);
My output:
helloooo...
helloooo...
helloooo...
helloooo...
0 <--- I am unsure what I am doing wrong because I cant seem to get this number to change at all....
Their template ( It was a fill in the blank ):
public class EchoTestDrive
public static void main(String [] args){
Echo e1 = new Echo();
int x = 0;
while(_________){
e1.hello();
if(___________){
e2.count = e2.count + e1.count;
x = x + 1;
System.out.println(e2.count);
class ________ {
int______ = 0;
void ______ {
System.out.println("helloooo... ");
Thanks fellow programmers and thanks for the assistance. To a bright future! :)
P.S. Is there a tip to figure out how to read the following output or what you will get without using the computer? It will be very helpful if you can describe what each part is doing.

public class Echo
    int count = 0;
    void hello(){
        System.out.println("helloooo... ");
public class EchoTestDrive
   public static void main(String [] args){
       Echo e1 = new Echo();
       Echo e2 = new Echo();
       int x = 0;
       while( x < 4 ){
           e1.hello();
           e1 = e2;
           // I intended to use this code because e1 is referring the Class Echo ->"hello()"
           // in the code above.  I was intending to make them both refer to that.
           // This way it print hello... 4 times when it goes in the loop.
           e1.count = e1.count + 1;
       if( x==4){
           e2.count = e2.count + e1.count;
        x = x + 1;
    System.out.println(e2.count);
}Edited by: Darryl Burke -- broke a long comment that was breaking the page formatting in some browsers

Similar Messages

  • The system variables in java, NEEDED ONLY at CLI execution of java programs

    The system variables in java, NEEDED ONLY at CLI execution of java programs, and NOT needed at all[essentially] if I install bundle(14+6.7)?
    if I install bundle(14+6.7) to run-test a web app with netbeans 6.7 what I must press, then opens the default browser? I have to be online,...? How I test browse my project?

    Probably a complete tutorial on all possible environment variables in addition to a tutorial on netbeans configuration.

  • Interaction with Microsoft Word using Java Programming

    writing Text ON TO MICROSOFT WORD USING java Programming Urgently required

    Go throuh jakarta POI(hssf) to do..No! HSSF which stands for Horrible SpreadSheet Format can be used for Excel (spreadsheets as the name suggests). For Word, you would need to lok at HPSF.

  • Need help with total in my mortgage program

    I have been work on this program and I can't seem to correct how the amount is shown. It gives several numbers after the decimal. Can anyone please help.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    /* Diana Saddler
    * PRG-421  Java Programming II
    public class mortgage extends JFrame implements ActionListener {
    private JPanel panelAdder;
    private JLabel labela;
    private JLabel labelt;
    private JLabel labelr;
    private JTextField textFieldAmount;
    private JTextField textFieldTerm;
    private JTextField textFieldRate;
    private JTextField textFieldResult;
    private JButton buttonCalc;
    public mortgage() {
      initComponents();
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      pack();
      // Add Listeners
      buttonCalc.addActionListener(this);
    public void initComponents() {
    //Initialize Components
    panelAdder = new JPanel();
    labela = new JLabel("Amount");
    textFieldAmount = new JTextField();
    labelt = new JLabel("Term");
    textFieldTerm = new JTextField();
    labelr = new JLabel("Rate");
    textFieldRate = new JTextField();
    textFieldResult = new JTextField();
    buttonCalc = new JButton("Calculate");
    //Set Object Attributes
    textFieldResult.setEditable(false);
    textFieldResult.setColumns(8);
    textFieldAmount.setColumns(6);
    textFieldTerm.setColumns(3);
    textFieldRate.setColumns(3);
    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    //Add the components to the panel
    panelAdder.add(labela);
    panelAdder.add(textFieldAmount);
    panelAdder.add(labelt);
    panelAdder.add(textFieldTerm);
    panelAdder.add(labelr);
    panelAdder.add(textFieldRate);
    panelAdder.add(buttonCalc);
    panelAdder.add(textFieldResult);
    contentPane.add(panelAdder);
        public static void main(String[] args) {
             mortgage frame = new mortgage();
    //calculate
        private void setResultValue() {
       double amount = Double.parseDouble(textFieldAmount.getText());
       double term = Integer.parseInt(textFieldTerm.getText());
       double rate = Double.parseDouble(textFieldRate.getText()) / 100.;
       double result = amount * ( rate * Math.pow ( ( 1 + rate ), term ) ) / ( Math.pow( ( 1 + rate ), term ) - 1 );
       textFieldResult.setText(Double.toString(result));
    public void actionPerformed(ActionEvent event) {
      System.out.println("Action Button");
      String command = event.getActionCommand();
      if ("Calculate".equals(command))
          setResultValue();
    }

    DecimalFormat

  • How can I run other programs using java program

    hi experts,
    I am trying to execute a set of commands from java program
    eg: from command prompt
    java CommandExecutor c:\winnt\notepad.exe c:\some.exe c:\onemorecommand.exe
    and inside the CommandExecutor main method..
    public static void main(String []arg)
    for(i = 0; i < arg.length; i++)
    Runtime.getRuntime().exec(arg(i));
    the above code is executing all the command one after the other, but I want to execute the above commands squentially, i.e I want to execute the second command only after finishing the first command and the third after finishing the second and so on depending upon the arguments passed, how can I acheive this...
    I have tried to use the Process which is returned by the exec(arg) method but the exitValue() returns same value before execution and after execution.
    thanks,
    krishna

    Did you try to get the process returned and then try
    process.waitFor() method. This waits for the process to finish.
    After that try the next execution

  • How to call a external program in java program

    for example, if I want to execute internet explore or windows word in java program, how to do it?

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html

  • (beginner) Need help with a client [Beginner]

    Hi, i'm danny and i'm following tutorials and lessons, and i created my own server and i tried to make my own webclient. My Teacher send me a webclient and he said that i only have to change the ip adress into mines (runescapeworld143.zapto.org) and compile it. The whole problem is now my teacher is on holiday and i called him if he would help me he said that i must ask it to the forums of oracle, so here is my question.
    Ok the source is here if you wanna download it [http://updatedannyskape.webs.com/client.jar.src.zip]
    My teacher say's that the current ip = 188.165.201.65:port43594
    and you have to change it in you're ip adress (runescapeworld143.zapto.org)
    but the problem is now i searched the whole document for 188.165.201.65 but i can't find it, can somebody help me out where i can find this?
    I also tried to compile the source but there are over the 100 errors
    Maybe this is because i created my own compiler ?
    I don't know but here is the compiler code
    @echo off
    cd .
    "C:\Program Files\Java\jdk1.6.0_20\bin\javac.exe" -sourcepath scr/*.java
    pause[Compiler error picture|http://updatedannyskape.webs.com/error.png]
    I hope you are able to help me, Already thanks !
    Edited by: Codenowy on Aug 18, 2010 1:21 PM
    Edited by: Codenowy on Aug 18, 2010 1:22 PM

    Open your file in QuickTime Player then press command & J keys to access the Properties window.
    Click on *Video Track* then *Other Settings*.
    Actvate the checkbox next to *Cache (hint)*.

  • [Beginner] Need Help with my source [Beginner]

    Hi, i'm danny and i'm following tutorials and lessons, and i created my own server and i tried to make my own webclient. My Teacher send me a webclient and he said that i only have to change the ip adress into mines (runescapeworld143.zapto.org) and compile it. The whole problem is now my teacher is on holiday and i called him if he would help me he said that i must ask it to the forums of oracle, so here is my question.
    Ok the source is here if you wanna download it [http://updatedannyskape.webs.com/client.jar.src.zip]
    My teacher say's that the current ip = 188.165.201.65:port43594
    and you have to change it in you're ip adress (runescapeworld143.zapto.org)
    but the problem is now i searched the whole document for 188.165.201.65 but i can't find it, can somebody help me out where i can find this?
    I also tried to compile the source but there are over the 100 errors
    Maybe this is because i created my own compiler ?
    I don't know but here is the compiler code
    @echo off
    cd .
    "C:\Program Files\Java\jdk1.6.0_20\bin\javac.exe" -sourcepath scr/*.java
    pause[Compiler error picture|http://updatedannyskape.webs.com/error.png]
    I hope you are able to help me, Already thanks !
    Edited by: Codenowy on Aug 18, 2010 1:21 PM
    Edited by: Codenowy on Aug 18, 2010 1:22 PM

    Or are there any files missing ?

  • Need urgent help in a simple java program that adds up even numbers and..

    The task is to write a program that allows the user to enter 8 integers and then displays the sum of the odd integers and the product of the even integers
    what i did so far is
    public class Computation
    private int n;
    private int even;
    private int odd;
    public Computation()
    even =0;
    odd = 1;
    public Computation(int num1, int num2, int num3,int num4,int num5,int num6,int num7, int num8)
    n = num1;
    n = num2;
    n = num3;
    n = num4;
    n = num5;
    n = num6;
    n = num7;
    n = num8;
    for(int i=0; i<=n; i++)
    if(n%2 == 0)
    even += n;
    else
    odd *=n;
    public int getEven(int n)
    return even;
    public int getOdd()
    return odd;
    import java.util.*;
    public class Tester
    public static void main(String [] args)
    System.out.println("Enter any three words");
    Scanner input = new Scanner(System.in);
    int num1 = input.nextInt();
    int num2 = input.nextInt();
    int num3 = input.nextInt();
    int num4 = input.nextInt();
    int num5 = input.nextInt();
    int num6 = input.nextInt();
    int num7 = input.nextInt();
    int num8 = input.nextInt();
    Computation compute = new Computation(num1, num2, num3, num4, num5, num6, num7, num8);
    System.out.println("The Summation of the even numbers is: " + compute.getEven( ) + "\n" +"The product of the odd numbers is: " + compute.getOdd());
    }The result i get is always zero.. however, i think the problem lies in the first class when i constructed the numbers and sat them all to one object "n",
    i need help in fixing this bug,,
    thanks

    7uSamx wrote:
    Can you illustrate by a small example please ?Any small example would already contain pretty much the entire code.
    You know how to declare a method, right? You have several in your code, so I assume you do.
    You already know how to check if a given variable is even or odd. You already showed that code, so I assume you do.
    Now put those two together and you'll have a method that decides if the value passed to it is even or odd.
    Now put the desired action in each of the branches of the if-statement and you're almost done.
    Now call the method with each method from your constructor and you're done.

  • Need help with search function in my program

    Hello all, some of you may remeber me from my previous inventory programs. Well I am finally on my last one and I need to add a search option to the code. Here is the class that will contain that option.
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Inventory2 extends JFrame implements ActionListener {
    //Utility class for displaying the picture
    //If we are going to use a class/method/variable inside that class only, we declare it private in that class
    private class MyPanel extends JPanel {
    ImageIcon image = new ImageIcon("Sample.jpg");
    int width = image.getIconWidth();
    int height = image.getIconHeight();
    long angle = 30;
    public MyPanel(){
    super();
    public void paintComponent(Graphics g){
         super.paintComponent(g);
         Graphics2D g2d = (Graphics2D)g;
         g2d.rotate (Math.toRadians(angle), 60+width/2, 60+height/2);
         g2d.drawImage(image.getImage(), 60, 60, this);
         g2d.dispose();
    }//end class MyPanel
    int currentIndex; //Currently displayed Item
    Product[] supplies = new Product[4];
    JLabel name ;
    JLabel number;
    JLabel rating;
    JLabel quantity;
    JLabel price;
    JLabel fee;
    JLabel totalValue;
    JTextField nameField = new JTextField(20);
    JTextField numberField = new JTextField(20);
    JTextField ratingField = new JTextField(20);
    JTextField quantityField = new JTextField(20);
    JTextField priceField = new JTextField(20);
    JPanel display;
    JPanel displayHolder;
    JPanel panel;
    boolean locked = false; //Notice how I've used this flag to keep the interface clean
    public Inventory2() {
    makeTheDataItems();
    setSize(700, 500);
    setTitle("Inventory Program");
    //make the panels
    display = new JPanel();
    JPanel other = new JPanel();
    other.setLayout(new GridLayout(2, 1));
    JPanel picture = new MyPanel();
    JPanel buttons = new JPanel();
    JPanel centerPanel = new JPanel();
    displayHolder = new JPanel();
    display.setLayout(new GridLayout(7, 1));
    //other.setLayout(new GridLayout(1, 1));
    //make the labels
    name = new     JLabel("Name :");
    number = new JLabel("Number :");
    rating = new JLabel("Rating     :");
    quantity = new JLabel("Quantity :");
    price = new JLabel("Price     :");
    fee = new JLabel("Restocking Fee (5%) :");
    totalValue = new JLabel("Total Value :");
    //Use the utility method to make the buttons
    JButton first = makeButton("First");
    JButton next = makeButton("Next");
    JButton previous = makeButton("Previous");
    JButton last = makeButton("Last");
    JButton search = makeButton("Search");
    //Other buttons
    JButton add = makeButton("Add");
    JButton modify = makeButton("Modify");
    JButton delete = makeButton("Delete");
    JButton save = makeButton("Save");
    JButton exit = makeButton("Exit");
    //Add the labels to the display panel
    display.add(name);
    display.add(number);
    display.add(rating);
    display.add(quantity);
    display.add(price);
    display.add(fee);
    //add the buttons to the buttonPanel
    buttons.add(first);
    buttons.add(previous);
    buttons.add(next);
    buttons.add(last);
    buttons.add(search);
    //Add the picture panel and display to the centerPanel
    displayHolder.add(display);
    centerPanel.setLayout(new GridLayout(2, 1));
    centerPanel.add(picture);
    centerPanel.add(displayHolder);
    other.add(buttons);
    JPanel forAdd = new JPanel(); // add the other buttons to this panel
    forAdd.add(add);
    forAdd.add(modify);
    forAdd.add(delete);
    forAdd.add(save);
    forAdd.add(exit);
    other.add(forAdd);
    //Add the panels to the frame
    getContentPane().add(centerPanel, "Center");
    getContentPane().add(other, "South");
    this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setVisible(true);
    private void makeTheDataItems () {
    Product p1 = new DVD("The one", 001, 200, 100, "The one");
    Product p2 = new DVD("Once upon a time in China V", 002, 500, 10000, "Once upon a time in China V");
    Product p3 = new DVD("Rat Race", 003, 100, 3000, "Rat Race");
    Product p4 = new DVD("The Man in the Iron Mask", 004, 3000, 9000, "The Man in the Iron Mask");
    supplies[0] = p1;
    supplies[1] = p2;
    supplies[2] = p3;
    supplies[3] = p4;
    //Utility method for creating and dressing buttons
    private JButton makeButton(String label) {
    JButton button = new JButton(label);
    button.setPreferredSize(new Dimension(100, 25));
    button.setActionCommand(label);
    button.addActionListener(this);
    return button;
    private void addItem() {
    panel = new JPanel();
    JPanel add = new JPanel();
    add.setLayout(new GridLayout(7, 2));
    JButton addIt = makeButton("Add Item");
    JLabel name = new JLabel("Name :");
    JLabel rating = new JLabel("Rating     :");
    JLabel quantity = new JLabel("Quantity :");
    JLabel price = new JLabel("Price     :");
    add.add(name); add.add(nameField);
    add.add(rating); add.add(ratingField);
    add.add(quantity); add.add(quantityField);
    add.add(price); add.add(priceField);
    panel.add(add);
    JPanel forAddIt = new JPanel();
    forAddIt.add(addIt);
    panel.add(forAddIt);
    displayHolder.remove(display);
    displayHolder.add(panel);
    //display = panel;
    this.setVisible(true);
    public static void main( String args[]) {
    new Inventory2().displayFirst(); //The main method should not have too much code
    } // end main method
    public void actionPerformed(ActionEvent event) {
      String command = event.getActionCommand(); //This retrieves the command that we set for the button
      //Always compare strings using the .equals method and not using ==
      if(command.equals("First")) {
       if(!locked) {
         displayFirst();
      else if(command.equals("Next")) {
       if(!locked) {
         displayNext();
      else if(command.equals("Previous")) {
       if(!locked) {
         displayPrevious();
      else if(command.equals("Last")) {
       if(!locked) {
         displayLast();
      else if(command.equals("Exit")) {
       this.dispose();
       System.exit(0);
      else if(command.equals("Add")) {
       if(!locked) {
         addItem();
         locked = true;
      else if(command.equals("Add Item")) {
       addItemToArray();
      else if(command.equals("Modify")) {
       if(!locked) {
         modify();
         locked = true;
      else if(command.equals("Update")) {
          if(!locked) {
         modifyItemInArray();
         locked = true;
      else if(command.equals("Delete")) {
       if(!locked) {
         DVD dvd = (DVD)supplies[currentIndex];
            int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete item "+dvd.getItemNumber());
                if(confirm == JOptionPane.YES_OPTION) {
          removeItemAt(currentIndex);
          displayFirst();
    private void modify() {
    DVD dvd = (DVD)supplies[currentIndex];
    panel = new JPanel();
    JPanel add = new JPanel();
    add.setLayout(new GridLayout(7, 2));
    JButton update = makeButton("Update");
    JLabel number = new JLabel("Number :");
    JLabel name = new JLabel("Name :");
    JLabel rating = new JLabel("Rating     :");
    JLabel quantity = new JLabel("Quantity :");
    JLabel price = new JLabel("Price     :");
    add.add(number);
    numberField.setText(""+dvd.getItemNumber()); numberField.setEditable(false); add.add(numberField);
    add.add(name);
    nameField.setText(dvd.getItemName()); add.add(nameField);
    ratingField.setText(dvd.getRating()); ratingField.setEditable(false);
    add.add(rating); add.add(ratingField);
    add.add(quantity);
    quantityField.setText(""+dvd.getStockQuantity());
    add.add(quantityField);
    add.add(price);
    add.add(priceField); priceField.setText(""+dvd.getItemPrice());
    panel.add(add);
    JPanel forAddIt = new JPanel();
    forAddIt.add(update);
    panel.add(forAddIt);
    displayHolder.remove(display);
    displayHolder.add(panel);
    //display = panel;
          this.setVisible(true);
    private void addItemToArray() {
    Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
    Double.parseDouble(priceField.getText()), ratingField.getText());
    //Extend size of array by one first
    Product[] ps = new Product[supplies.length + 1];
    for(int i = 0; i < ps.length-1; i++) {
    ps[i] = supplies;
    ps[supplies.length] = p;
    supplies = ps;
    displayHolder.remove(panel);
    displayHolder.add(display);
    displayLast();
    this.setVisible(false);
    this.setVisible(true);
    //Utility method to ease the typing and reuse code
    //This method reduces the number of lines of our code
    private void displayItemAt(int index) {
    DVD product = (DVD)supplies[index];
    name.setText("Item Name: "+ product.getItemName());
    number.setText("Item Number: "+ product.getItemNumber());
    rating.setText("Rating: "+ product.getRating());
    quantity.setText("Quantity In Stock: "+ product.getStockQuantity());
    price.setText("Item Price: "+ product.getItemPrice());
    totalValue.setText("Total: " + product.calculateInventoryValue());
    fee.setText("Restocking Fee (5%) :"+product.calculateRestockFee());
    locked = false;
    this.repaint();
    this.setVisible(true);
    private void modifyItemInArray() {
    Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
    Double.parseDouble(priceField.getText()), ratingField.getText());
    supplies[currentIndex] = p;
    displayHolder.remove(panel);
    displayHolder.add(display);
         displayItemAt(currentIndex);
    this.setVisible(false);
    this.setVisible(true);
    private void removeItemAt(int index) {
    Product[] temp = new Product[supplies.length-1];
    int counter = 0;
    for(int i = 0; i < supplies.length;i++) {
    if(i == index) { //skip the item to delete
    else {
         temp[counter++] = supplies[i];
    supplies = temp;
    public void displayFirst() {
    displayItemAt(0);
    currentIndex = 0;
    public void displayNext() {
    if(currentIndex == supplies.length-1) {
    displayFirst();
    currentIndex = 0;
    else {
    displayItemAt(currentIndex + 1);
    currentIndex++;
    public void displayPrevious() {
    if(currentIndex == 0) {
    displayLast();
    currentIndex = supplies.length-1;
    else {
    displayItemAt(currentIndex - 1);
    currentIndex--;
    public void displayLast() {
    displayItemAt(supplies.length-1);
    currentIndex = supplies.length-1;
    }//end class Inventory2
    I am not sure where to put it and how to set it up. If you guys need the other two classes let me know. Thanks in advanced.

    Here are the other two classes:
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class Product implements Comparable {
    String name;
    int number;
    long stockQuantity;
    double price;
    public Product() {
      name = "";
          number = 0;
          stockQuantity = 0L;
          price = 0.0;
    public Product(String name, int number, long stockQuantity, double price) {
      this.name = name;
          this.number = number;
          this.stockQuantity = stockQuantity;
          this.price = price;
         public void setItemName(String name) {
      this.name = name;
    public String getItemName() {
      return name;
    public void setItemNumber(int number) {
      this.number = number;
    public int getItemNumber() {
      return number;
    public void setStockQuantity(long quantity) {
      stockQuantity = quantity;
    public long getStockQuantity() {
      return stockQuantity;
    public void setItemPrice(double price) {
      this.price = price;
    public double getItemPrice() {
      return price;
    public double calculateInventoryValue() {
      return getItemPrice() * getStockQuantity();
    public int compareTo (Object o) {
      Product p = (Product)o;
      return name.compareTo(p.getItemName());
    public String toString() {
      return "Name :"+getItemName() + "\nNumber"+number+"\nPrice"+price+"\nQuantity"+stockQuantity + "\nValue :"+calculateInventoryValue();
    class DVD extends Product implements Comparable {
    private String rating;
    public DVD() {
      super(); //Call the constructor in Product
      rating = ""; //Add the additonal attribute
    public DVD(String name, int number, long stockQuantity, double price, String rating) {
      super(name, number, stockQuantity, price); //Call the constructor in Product
      this.rating = rating; //Add the additonal attribute
         public void setRating(String rating) {
      this.rating = rating;
    public String getRating() {
      return rating;
    public double calculateInventoryValue() {
      return getItemPrice() * getStockQuantity() + getItemPrice()*getStockQuantity()*0.05;
    public double calculateRestockFee() {
      return getItemPrice() * 0.05;
    public int compareTo (Object o) {
      Product p = (Product)o;
      return getItemName().compareTo(p.getItemName());
    public String toString() {
      return "Name :"+getItemName() + "\nNumber"+getItemNumber()+"\nPrice"+getItemPrice()+"\nQuantity"+getStockQuantity() +"\nRating :"+getRating()+"\nValue"+calculateInventoryValue();
    }You should be able to search through these items, and any other items that have been added to the program.

  • Need HELP with objects and classes problem (program compiles)

    Alright guys, it is a homework problem but I have definitely put in the work. I believe I have everything right except for the toString method in my Line class. The program compiles and runs but I am not getting the right outcome and I am missing parts. I will post my problems after the code. I will post the assignment (sorry, its long) also. If anyone could help I would appreciate it. It is due on Monday so I am strapped for time.
    Assignment:
    -There are two ways to uniquely determine a line represented by the equation y=ax+b, where a is the slope and b is the yIntercept.
    a)two diffrent points
    b)a point and a slope
    !!!write a program that consists of three classes:
    1)Point class: all data MUST be private
    a)MUST contain the following methods:
    a1)public Point(double x, double y)
    a2)public double x ()
    a3public double y ()
    a4)public String toString () : that returns the point in the format "(x,y)"
    2)Line class: all data MUST be private
    b)MUST contain the following methods:
    b1)public Line (Point point1, Point point2)
    b2)public Line (Point point1, double slope)
    b3)public String toString() : that returns the a text description for the line is y=ax+b format
    3)Point2Line class
    c1)reads the coordinates of a point and a slope and displays the line equation
    c2)reads the coordinates of another point (if the same points, prompt the user to change points) and displays the line equation
    ***I will worry about the user input later, right now I am using set coordinates
    What is expected when the program is ran: example
    please input x coordinate of the 1st point: 5
    please input y coordinate of the 1st point: -4
    please input slope: -2
    the equation of the 1st line is: y = -2.0x+6.0
    please input x coordinate of the 2nd point: 5
    please input y coordinate of the 2nd point: -4
    it needs to be a diffrent point from (5.0,-4.0)
    please input x coordinate of the 2nd point: -1
    please input y coordinate of the 2nd point: 2
    the equation of the 2nd line is: y = -1.0x +1.0
    CODE::
    public class Point{
         private double x = 0;
         private double y = 0;
         public Point(){
         public Point(double x, double y){
              this.x = x;
              this.y = y;
         public double getX(){
              return x;
         public double setX(){
              return this.x;
         public double getY(){
              return y;
         public double setY(){
              return this.y;
         public String toString(){
              return "The point is " + this.x + ", " + this.y;
    public class Line
         private double x = 0;
         private double y = 0;
         private double m = 0;
         private double x2 = 0;
         private double y2 = 0;
         public Line()
         public Line (Point point1, Point point2)
              this.x = point1.getX();
              this.y = point1.getY();
              this.x2 = point2.getX();
              this.y2 = point2.getY();
              this.m = slope(point1, point2);
         public Line (Point point1, double slope)
              this.x = point1.getX();
              this.y = point1.getY();
         public double slope(Point point1, Point point2)//finds slope
              double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
              return m1;
         public String toString()
              double temp = this.x- this.x2;
              return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
              //y-y1=m(x-x1)
    public class Point2Line
         public static void main(String[]args)
              Point p = new Point(3, -3);
              Point x = new Point(10, 7);
              Line l = new Line(p, x);
              System.out.println(l.toString());
    }My problems:
    I dont have the right outcome due to I don't know how to set up the toString in the Line class.
    I don't know where to put if statements for if the points are the same and you need to prompt the user to put in a different 2nd point
    I don't know where to put in if statements for the special cases such as if the line the user puts in is a horizontal or vertical line (such as x=4.7 or y=3.4)
    Edited by: ta.barber on Apr 20, 2008 9:44 AM
    Edited by: ta.barber on Apr 20, 2008 9:46 AM
    Edited by: ta.barber on Apr 20, 2008 10:04 AM

    Sorry guys, I was just trying to be thorough with the assignment. Its not that if the number is valid, its that you cannot put in the same coordinated twice.
    public class Line
         private double x = 0;
         private double y = 0;
         private double m = 0;
         private double x2 = 0;
         private double y2 = 0;
         public Line()
         public Line (Point point1, Point point2)
              this.x = point1.getX();
              this.y = point1.getY();
              this.x2 = point2.getX();
              this.y2 = point2.getY();
              this.m = slope(point1, point2);
         public Line (Point point1, double slope)
              this.x = point1.getX();
              this.y = point1.getY();
         public double slope(Point point1, Point point2)//finds slope
              double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
              return m1;
         public String toString()
              double temp = this.x- this.x2;
              return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
              //y-y1=m(x-x1)
    public class Point2Line
         public static void main(String[]args)
              Point p = new Point(3, -3);
              Point x = new Point(10, 7);
              Line l = new Line(p, x);
              System.out.println(l.toString());
    }The problem is in these lines of code.
    public double slope(Point point1, Point point2) //if this method finds the slope than how would i use the the two coordinates plus "m1" to
              double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
              return m1;
         public String toString()
              double temp = this.x- this.x2;
              return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
              //y-y1=m(x-x1)
         }if slope method finds the slope than how would i use the the two coordinates + "m1" to create a the line in toString?

  • Need help with algorithm for my paint program

    I was making a paint program with using a BufferedImage where the user draws to the BufferedImage and then I draw the BufferedImage onto the class I am extending JPanel with. I want the user to be able to use an undo feature via ctrl+z and I also want them to be able to update what kind of paper they're writing on live: a) blank paper b) graph paper c) lined paper. I cannot see how to do this by using BufferedImages. Is there something I'm missing or must I do it another way? I am trying to avoid the other way because it seems too demanding on the computer but if this is not do-able then I guess I must but I feel I should ask you guys if what I am doing is logical or monstrous.
    What I am planning to do is make a LinkedList that has the following 4 parameters:
    1) previous Point
    2) current Point
    3) current Color
    4) boolean connectPrevious
    which means that the program would basically draw the instantaneous line using the two points and color specified in paintComponent(Graphics g). The boolean value is for ctrl+z (undo) purposes. I am also planning to use a background thread to eliminate repeated entries in the LinkedList except for the last 25 components of the LinkedList (that number might change in practice).
    What do you guys think?
    Any input would be greatly appreciated!
    Thanks in advance!

    Look at the package javax.swing.undo package - UndoableEdit interface and UndoManager class.
    Just implement the interface. Store all necessary data to perform your action (colors, pixels, shapes etc.). Add all your UndoableEdits in an UndoManager instance and call undo() redo() when you need.

  • Need help with signing up for dev program - questions

    Greetings,
    I am planning on signing up for the dev program and I will be making a game to upload into the apple store. When I try sign up for the dev program/apple id, my country is not in the available list of countries. I am currently living in Mongolia and there is no itunes store available here. Would I be able to sign up for the dev program and develop/upload/sell?

    I am able to use the singapore store as I made this account using singapore as my region. If I do that with my dev account, will I not run into problems with billing/confirmation issues?

  • Need help with updates and new apple programs

    something happened to my pc. having problems with my pc when it restarts.
    wondered if anyone whichapple updates require a restart, and which don't?
    if they require a restart to finish installation, they fail, and my pc crashes, and i have to resintall os.
    i know the iwork does not require a restart, where ilife does. so for now, i can install iwork, but not ilife.
    in anyone familiar with 10.5.6 knows which updates/add ond require a restart and which don't, please post. any help appreciated. 4th re install now.

    Hey network --
    Sorry to hear of your problems . . .
    What Mac are you running there?
    Did the installation of 10.5.6 finally go well?
    You're having problems with iLife, but what about Snow Leopard?

  • I need help with copying files in java?

    hi, i use the following code sample to copy a directory structure and its files.
    It copy's the directory-structure, but all the files in it have 0kb as size. except one file.
    Here's the code:
    public static void copyDir(String source, String target)
    String [] listing = new String [0];
    FileReader in = null;
    FileWriter out = null;
    String sourcePath = source;
    String targetPath = target;
    // Maakt directory onder target directory
    File f = new File(targetPath);
    f.mkdir();
    // Maakt filelist van bestanden in source-directory
    f = new File(sourcePath);
    listing = f.list();
    for(int i = 0; i < listing.length; i++)
    f = new File(sourcePath + listing);
    if(f.isDirectory())
    copyDir(source + listing[i] + File.separatorChar,
    target + listing[i] + File.separatorChar);
    else
    try
    in = new FileReader(sourcePath + listing[i]);
    out = new FileWriter(targetPath + listing[i]);
    int t;
    while (-1 != (t = in.read()))
    out.write(t);
    try { Thread.sleep(200); } catch (InterruptedException e) { }
    System.out.println("Copied: " + sourcePath + listing[i]);
    catch (Exception e)
    System.out.println(e);

    Here is a quick copy program that works. You'll need to deal with the exception instead of just throwing it though.
    import java.io.*;
    public class Copy
      private static void copy(String source, String target) throws IOException
        // Create directory
        File file=new File(target);
        file.mkdirs();
        // Get contents
        file=new File(source);
        File[] files=file.listFiles();
        // Copy files
        int length;
        byte[] buffer=new byte[1024];
        for(int i=0; i<files.length; i++)
          String destination=target+File.separator+files[ i ].getName();
          if(files[ i ].isDirectory())
            copy(files[ i ].getPath(), destination);
          else
            FileInputStream in=new FileInputStream(files[ i ]);
            FileOutputStream out=new FileOutputStream(destination);
            while((length=in.read(buffer))!=-1)
              out.write(buffer, 0, length);
            in.close();
            out.close();
      public static void main(String[] args) throws IOException
        copy(args[0], args[1]);
    }[\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for