:o does anyone know how to write this for me i have no idea i need help
Outline: Java is a powerful Object Oriented Programming (OOP) language specifically designed for use with the internet. However, this makes learning Java fairly difficult. So we will start with a simple (text-based) program.

You should be familiar with the x-y real number plane used in co-ordinate geometry:


Positions on this plane are given as (x,y) co-ordinate pairs relative to the x and y axes.

The distance between any two points P1 = (x1, y1) and P2 = (x2, y2) is given by the distance formula, derived from Pythagoras' Theorem:

What to do: You are required to design and implement a java program to calculate and display (as text) the distance between pairs of (x,y) points supplied from a text file.

The file is named data.txt and contains one pair of points per line in the format: (x1,y1)<tab>(x2,y2) where <tab> refers to a single tab (ASCII 9) character. You will need to create your own data.txt file to test your program. By default, this file must be stored inside the Build folder of your project.

The program should display a title and brief description of what it does. Each pair of points should be displayed, along with the distance between them, correct to 4 decimal places eg:

The distance between (0,0) and (1,5) is 5.0990

(this thread was started by a friend of mine needing the same help, he just used my account to post the thread)

So yeah... any help would be appreciated

So, what has your friend done so far with his project?

This sounds like homework. We don't do homework for people; we help people with what they're working on. Please post some code they've done on their own.

Ok guys, I kinda have what you are looking for.

The only change is that my text file does not contain any brackets or commas i.e (20,20) = 20 20.

The x1 coordinate is entered then SPACE then y1 coordinate entered,
then TAB
then x2 coordinate is entered then SPACE then y2 coordinate entered.

I dont have a solution for breaking down a string to search for numbers in that string.

The text file attached looks like this (test4.txt)

-------------------------------------------
0[SPACE]0[TAB]1[SPACE]5
10[SPACE]20[TAB]    30[SPACE]35
20[SPACE]34[TAB]    35[SPACE]43
-------------------------------------------------

The class that drives the show, also attached (test4.java)

-------------------------------------------------
public static void main(String[] args)
{
StringTokenizer token;
String tokenString = null;


String x1Cord = null;
String y1Cord = null;
String x2Cord = null;
String y2Cord = null;


BufferedReader buffer = null;
DecimalFormat df = new DecimalFormat("0.0000");


try
{
buffer = new BufferedReader(new FileReader("test4.txt"));
}
catch (FileNotFoundException fnf)
{
System.err.print("\nError: Cannot find " + "\"test4.txt\"" +
" file\n");
System.exit(1);
}


//display a title
System.out.println("\n*************************************");
System.out.println("** Co-ordinate System v1.0 **********");
System.out.println("*************************************");
System.out.println("\nPROGRAM DETAILS: ");
System.out.println("\tRead in two co-ordinates from the text file ");
System.out.println("\tWork out the difference betweeen them");
System.out.println("\nThe format in the text file is: x1 SPACE y1 TAB x2 SPACE y2");
System.out.println("I did not include the brackets/commas for the co-ordinates in ");
System.out.println("the text file as it involves alot of coding to remove!!");


while (true)
{
try
{
tokenString = buffer.readLine();
if (tokenString == null)
{
break;
}
}
catch (IOException ioe)
{
System.err.print("\nError: There was problem reading the File");
break;
}


//tab  & space is the delimeter
token = new StringTokenizer(tokenString, " \t");


x1Cord = token.nextToken();
y1Cord = token.nextToken();
x2Cord = token.nextToken();
y2Cord = token.nextToken();


//variables for the maths
double a;
double b;
double diff;
double x1 = Double.parseDouble(x1Cord);
double y1 = Double.parseDouble(y1Cord);
double x2 = Double.parseDouble(x2Cord);
double y2 = Double.parseDouble(y2Cord);


//do the pythagoras maths
a = y2 - y1;
b = x2 - x1;
diff = Math.sqrt( (a*a) + (b*b) );


//print out the co-ordinates
System.out.print("\nYour first point is:" + "(" + x1 + "," + y1 + ")");
System.out.println(" & Your second point is:" + "(" + x2 + "," + y2+ ")");


//This prints out the difference correct to 4 d.p. using DecimalFormat
System.out.println("Difference: " + df.format(diff));
}
}//end main
------------------------------------------------------------The output from the above files: 


*************************************
** Co-ordinate System v1.0 **********
*************************************
PROGRAM DETAILS:
Read in two co-ordinates from the text file
Work out the difference betweeen them


The format in the text file is: x1 SPACE y1 TAB x2 SPACE y2
I did not include the brackets/commas for the co-ordinates in
the text file as it involves alot of coding to remove!!


Your first point is: (0.0,0.0) & Your second point is: (1.0,5.0)
Difference: 5.0990


-------------------------------------------------------

Hope that gets you started, leave feedback! rickster.

HI guys, your code is soooo amazing~ i am doing something similar too but kinda stuck hope you can help me pleaseeee.basically i am also calculating the distance, but instead of having all the co ordinates typed in a text file, i am having a fill in blank for user to fill in the TO and FORM then i want it to search through my SQL database to find the matching co ordinates. for example user fill in TO: SE1 FROM SW5, then it will search the database to find the co ordinates of SE1 and SW 5 then cauculate. is that possible??? please help~ i was searching all night but no clue.

HI guys, your code is soooo amazing~ i am doing something similar too but kinda stuck hope you can help me pleaseeee.basically i am also calculating the distance, but instead of having all the co ordinates typed in a text file, i am having a fill in blank for user to fill in the TO and FORM then i want it to search through my SQL database to find the matching co ordinates. for example user fill in TO: SE1 FROM SW5, then it will search the database to find the co ordinates of SE1 and SW 5 then cauculate. is that possible??? please help~ i was searching all night but no clue.

Searching internet all night LOL :lol:

Common sence my friend,
1. database with table contatining destination(example E2) and values to coordinates x & y
2. From form either in swing/JSP, you didn't say which one, you read two destinations
- check if their are not same as there is zore distance and no point to access database and run calculation
3. Connect to database get coordinates for your two destinations and run calculation

wowoooooooooo thanks!!!! so clever!!!!!!!!! so thats not hard at all yeah?? connecting SQL and java and transfering to and from

wowoooooooooo thanks!!!! so clever!!!!!!!!! so thats not hard at all yeah?? connecting SQL and java and transfering to and from

I don't see a problem there :cool: . They must showed you at school how to do it and query language is not so complex. Plus there is MySQL website with full documentation and lot of examples and if you look in daniweb MySQL section you get also lot of help there

well, you can't expect someone who responds to a post that's going on 3 years old with a poorly worded message that says how great the post is to be all that bright :)

LOL, I didn't check date

Hi ~ I have done this so far....a entryfield for user to type in the TO and FROM postcode, then I connect to the sql database...but I still cant find out how to READ the X and Y from the sql table then calculate using them..I got the table in database set up...a table of postcodeand its x and y points. Please help~ appreciate alot

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.EventObject;
import java.io.*;
import java.sql.*;
public class EntryCreateDialog extends JDialog
{ private JPanel bottom; /* Contains buttons: */
  private JButton okButton, cancelButton;
/* The panel with the entry fields: */
  private CreateDialogPanel dialogPanel;
  private String defaultFrom = ""; 
  private String defaultTo = "";

  private String newFrom; 
  private String newTo;

  public EntryCreateDialog(JFrame owner)
  { 
    super(owner, "Distance Calculating system", true);
  /* Create the subcomponents: */
    okButton = new JButton("GetDistance");
    cancelButton = new JButton("Cancel");
  /* Instance of nested 
   * class for event handling: */
    ButtonHandler bHandler = new ButtonHandler();
    GetDistanceButton.addActionListener(bHandler);
    cancelButton.addActionListener(bHandler);

    bottom = new JPanel();
    bottom.add(GetDistanceButton);      // Uses the implicit flow
    bottom.add(cancelButton);  // layout of JPanel. 

    bottom.setBorder(
        BorderFactory.createEtchedBorder());
    dialogPanel = new CreateDialogPanel();
  /* Dialog is given a Border Layout: */
    getContentPane().setLayout(new BorderLayout());
  /* Put button panel at base of dialog: */    
    getContentPane().add(bottom, 
                         BorderLayout.SOUTH); 
    getContentPane().add(dialogPanel, 
                         BorderLayout.CENTER); 
  }
  public void setOldFields(Varchar from, Varchar to)
{ defaultFrom = from;
  defaultTo = to;
  dialogPanel.setOldFields(from,to); 
}
public void setFields(Varchar from, Varchar to)
{ newFrom = from; 
  newTo = to;

}

public String getFrom() 
{ return newFrom; } 
public String getTo() 
{ return newTo; }

class ButtonHandler 
implements ActionListener
{ public void actionPerformed(ActionEvent ev)
  { JButton button = (JButton) ev.getSource();
    String label = button.getText();
    if ("GetDistance".equals(label))

class customersDB

    public customersDb(String customers)
  { try 
    { String s = "jdbc:odbc:" + customers; 
      con = DriverManager.getConnection(s);
      System.out.println("Connection established"); 
      entryId = getMaxId();
    } 
    catch(SQLException sqle)
    { handleException(sqle); } 
  }

  private void handleException(SQLException e)
  { e.printStackTrace();
    while (e != null)
    { System.out.println("SQLState: " + e.getSQLState());
      System.out.println("Message: " + e.getMessage());
      System.out.println("Code: " + e.getErrorCode());
      e.getNextException();
    }
  }




    else /* Cancel pressed */
    { setFields(null,null,null); }
    dialogPanel.reset();
    setVisible(false);  // close dialog. 
  } 
 } /* End of nested class */
} /* End of EntryCreateDialog */

You need to check your coding first, you have lot of mistakes there!

and I will give small example of working with database
establish connection with database

try
{
	conn = DriverManager.getConnection("jdbc:mysql://db_location/" 
		+ "database_name?user=user_name&password=user_password");
	stmt = conn.createStatement();
}
catch(SQLException ex)
{
	System.out.println("SQLException : " + ex.getMessage() );
}

Run query (get data grom db)

try
{				
	int i=0;
	String strQuery = "select event_type, ev_date, ev_time, 
       ev_description from calendar_events where userName='" 
	+ nUser.getUsername() + "' and cal_id='" + nUser.getCalId() + "'";
	rs = stmt.executeQuery( strQuery);
	while( rs.next())
	{
		eArr[i] = new CalendarData();
		eArr[i].setEventType(rs.getString("event_type") );
		eArr[i].setEventDate(rs.getString("ev_date") );
		eArr[i].setEventTime(rs.getInt("ev_time") );
		eArr[i].setEventDescription(rs.getString("ev_description") );
		i++;					
	} // end while loop
}//end try
catch(SQLException ex)
{
	System.out.println("SQLException : " + ex.getMessage() );
}	// end catch

and close conection

try
{
	if( stmt !=null) stmt.close();
	if(conn != null) conn.close();
}
catch(SQLException ex)
{
	System.out.println("SQLException : " + ex.getMessage() );
}

PS: For futhure, can you please use tag for inserting code into post, it is the # (hash) in post toolbar. Thanx

and make sure your database resources are ALWAYS returned by closing them in the finally block of the method in which you created them!

OK~ so mayb like this? Sorry i seems so stupid...but i really wanna get it working...>.< really appreciate your help

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.EventObject;
import java.io.*;
import java.sql.*;
public class DistanceCalculationSystem extends JDialog
{ private JPanel bottom; /* Contains buttons: */
  private JButton okButton, cancelButton;
/* The panel with the entry fields: */
  private CreateDialogPanel dialogPanel;
  private String defaultFrom = ""; 
  private String defaultTo = "";
  
  private String newFrom; 
  private String newTo;
     
  public EntryCreateDialog(JFrame owner)
  { 
    super(owner, "Distance Calculating system", true);
  /* Create the subcomponents: */
    okButton = new JButton("GetDistance");
    cancelButton = new JButton("Cancel");
  /* Instance of nested 
   * class for event handling: */
    ButtonHandler bHandler = new ButtonHandler();
    GetDistanceButton.addActionListener(bHandler);
    cancelButton.addActionListener(bHandler);
      
    bottom = new JPanel();
    bottom.add(GetDistanceButton);      // Uses the implicit flow
    bottom.add(cancelButton);  // layout of JPanel. 
    
    bottom.setBorder(
        BorderFactory.createEtchedBorder());
    dialogPanel = new CreateDialogPanel();
  /* Dialog is given a Border Layout: */
    getContentPane().setLayout(new BorderLayout());
  /* Put button panel at base of dialog: */    
    getContentPane().add(bottom, 
                         BorderLayout.SOUTH); 
    getContentPane().add(dialogPanel, 
                         BorderLayout.CENTER); 
  }
  public void setOldFields(Varchar from, Varchar to)
{ defaultFrom = from;
  defaultTo = to;
  dialogPanel.setOldFields(from,to); 
 
}
 public static void main(string[] args)
 { ConsoleReader in = new ConsoleReader(System.in);
 
 var v1 = in.readVar;
 var v2 = in.readVar;
public void setFields(Varchar from, Varchar to)
{ newFrom = from; 
  newTo = to;
 
}
 
public String getFrom() 
{ return newFrom; } 
public String getTo() 
{ return newTo; }

class ButtonHandler 
implements ActionListener
{ public void actionPerformed(ActionEvent ev)
  { JButton button = (JButton) ev.getSource();
    String label = button.getText();
    if ("GetDistance".equals(label))
    
class customersDB {  
      
    public static void main (String[] args) {  
        try {  
            // Step 1: Load the JDBC driver.  
            Class.forName("com.mysql.jdbc.Driver");  
            // Step 2: Establish the connection to the database.  
            String url = "jdbc:mysql://127.0.0.1:3306/customers >>postcode_table";  
            Connection conn = DriverManager.getConnection(url,"crystal","pass");   
        } catch (Exception e) {  
            System.err.println("Got an exception! ");  
            System.err.println(e.getMessage());  
        }  
    }  
} 
try
{    
 int i=0;
 String strQuery = "select post_code, x-co, y-co, 
        from postcode_table where post_code='v1" 
 + nUser.getpost_code() + "' and post_code='v2" + nUser.getpost_code() + "'";
 rs = stmt.executeQuery( strQuery);
 while( rs.next())
 {
  eArr[i] = new data();
  eArr[i].setpostcode(rs.getvarchar("postcode") );
  eArr[i].setx-co(rs.getdecimal("x1") );
  eArr[i].sety-co(rs.getdecimal("y1") );
  
  eArr[n] = new data();
  eArr[n].setpostcode(rs.getvarchar("postcode") );
  eArr[n].setx-co(rs.getdecimal("x2") );
  eArr[n].sety-co(rs.getdecimal("y2") );
  
  i++;     
 } // end while loop
a = y2 - y1;
b = x2 - x1;
diff = Math.sqrt( (a*a) + (b*b) );
System.out.println("Difference: " + df.format(diff));

}//end try
catch(SQLException ex)
{
 System.out.println("SQLException : " + ex.getMessage() );
} // end catch

  
  
    
    
    else /* Cancel pressed */
    { setFields(null,null,null); }
    dialogPanel.reset();
    setVisible(false);  // close dialog. 
  } 
 } /* End of nested class */
} /* End of EntryCreateDialog */

~

Hi I am the stupid girl again..>< forget about the previous reply..mayb i should make myself abit more clear...this is what i want to have eg

entry field:
From:----------(user enter)
To:-------------(user enter)

then it read what the use typed (eg SW1 and SE1) then it search my DB for SW1 and SE1 and return the x and y co ordinates of SW1 and SE1. then it do the pythagorus on those x and y co ordinates..

is this very wrong?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.EventObject;
public class distancesystem extends JPanel
{ private JLabel fromLabel; 
  private JTextField fromField; 
  private JLabel toLabel;
  private JTextField toField;  
   
  public CreateDialogPanel()
  { /* Create subcomponents: */
    fromLabel = new JLabel("From:"); 
    fromField = new JTextField(); 
    toLabel = new JLabel("To:");
    toField = new JTextField();
     
    setBorder(
      BorderFactory.createTitledBorder("Create fields")); 
       
    add(fromLabel);      // Add the subcomponents in 
    add(fromField);      // the order they should appear
    add(toLabel);   // in the dialog. 
    add(toField);
  
  }
  public void setOldFields(Varchar from, Varchar to,
                                       )
  { fromField.setText(from); 
    toField.setText(to);
     
  }
  public Dimension getPreferredSize()
  { return new Dimension(400,120); }
  public Dimension getMinimumSize()
  { return new Dimension(400,120); }
  /* Customised layout method, fixed positions
    (xstart,ystart,width,height) for components: */
  public void doLayout()
  { nameLabel.setBounds(10,10,90,30);
    nameField.setBounds(100,15,270,20);
    addressLabel.setBounds(10,40,90,30);
    addressField.setBounds(100,45,270,20);
    phoneLabel.setBounds(10,70,90,30);
    phoneField.setBounds(100,75,270,20); 
  }
  public void reset()
  { fromField.setText(""); 
    toField.setText("");
   
  }
  public String getFrom() 
  { return fromField.getText(); } 
  public String getTo()
  { return toField.getText(); }
}
public class DistanceCalculationSystem extends JDialog
{ private JPanel bottom; /* Contains buttons: */
  private JButton okButton, cancelButton;
/* The panel with the entry fields: */
  private CreateDialogPanel dialogPanel;
  private String defaultFrom = ""; 
  private String defaultTo = "";
  
  private String newFrom; 
  private String newTo;
     
  public EntryCreateDialog(JFrame owner)
  { 
    super(owner, "Distance Calculating system", true);
  /* Create the subcomponents: */
    okButton = new JButton("GetDistance");
    cancelButton = new JButton("Cancel");
  /* Instance of nested 
   * class for event handling: */
    ButtonHandler bHandler = new ButtonHandler();
    GetDistanceButton.addActionListener(bHandler);
    cancelButton.addActionListener(bHandler);
      
    bottom = new JPanel();
    bottom.add(GetDistanceButton);      // Uses the implicit flow
    bottom.add(cancelButton);  // layout of JPanel. 
    
    bottom.setBorder(
        BorderFactory.createEtchedBorder());
    dialogPanel = new CreateDialogPanel();
  /* Dialog is given a Border Layout: */
    getContentPane().setLayout(new BorderLayout());
  /* Put button panel at base of dialog: */    
    getContentPane().add(bottom, 
                         BorderLayout.SOUTH); 
    getContentPane().add(dialogPanel, 
                         BorderLayout.CENTER); 
  }
  public void setOldFields(Varchar from, Varchar to)
{ defaultFrom = from;
  defaultTo = to;
  dialogPanel.setOldFields(from,to); 
 
}
public void setFields(Varchar from, Varchar to)
{ newFrom = from; 
  newTo = to;
 
}
 
public String getFrom() 
{ return newFrom; } 
public String getTo() 
{ return newTo; }

class ButtonHandler 
implements ActionListener
{ public void actionPerformed(ActionEvent ev)
  { JButton button = (JButton) ev.getSource();
    String label = button.getText();
    if ("GetDistance".equals(label))
    
    { setFields(dialogPanel.getFrom(),
          dialogPanel.getTo(),
          );
    }
    
class customersDB {  
      
    public static void main (String[] args) {  
        try {  
            // Step 1: Load the JDBC driver.  
            Class.forName("com.mysql.jdbc.Driver");  
            // Step 2: Establish the connection to the database.  
            String url = "jdbc:mysql://127.0.0.1:3306/customers >>postcode_table";  
            Connection conn = DriverManager.getConnection(url,"crystal","pass");   
        } catch (Exception e) {  
            System.err.println("Got an exception! ");  
            System.err.println(e.getMessage());  
        }  
    }  
} 
try
{    
 int i=0;
 String strQuery = "select post_code, x-co, y-co, 
        from postcode_table where post_code='to" 
 + nUser.getpost_code() + "' and post_code='from" + nUser.getpost_code() + "'";
 rs = stmt.executeQuery( strQuery);
 while( rs.next())
 {
  eArr[i] = new data();
  eArr[i].setpostcode(rs.getvarchar("postcode") );
  eArr[i].setx-co(rs.getdecimal("x1") );
  eArr[i].sety-co(rs.getdecimal("y1") );
  
  eArr[n] = new data();
  eArr[n].setpostcode(rs.getvarchar("postcode") );
  eArr[n].setx-co(rs.getdecimal("x2") );
  eArr[n].sety-co(rs.getdecimal("y2") );
  
  i++;     
 } // end while loop
a = y2 - y1;
b = x2 - x1;
diff = Math.sqrt( (a*a) + (b*b) );
System.out.println("Difference: " + df.format(diff));

}//end try
catch(SQLException ex)
{
 System.out.println("SQLException : " + ex.getMessage() );
} // end catch

  
  
    
    
    else /* Cancel pressed */
    { setFields(null,null,null); }
    dialogPanel.reset();
    setVisible(false);  // close dialog. 
  } 
 } /* End of nested class */
} /* End of EntryCreateDialog */

Is there a way to compare two sets of coordinates in a way which will tell you which point is closer to the origin? This is part of an assignment for a comp science class I'm taking.

[The so-and-so trucking company tracks the location of each of its trucks on a grid similar to an (x,y) plane. The home office is at location (0,0)//origin. Each collection contains 4 integers: the x-coordinate and then the y-coordinate of truck A followed by the x&y for truck B.]

I've manipulated the test4.java file to accept keyboard inputs for both sets of coordinates but I'm not sure how to compare the two to each other in relation to the origin.

Yes there is.

Now, to find out about it, Start your own thread, rather than hijacking this one, post the code you already have (you have some don't you) and ask a specific question about what is troubling you with it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.