struct
Point in a C/C++ program.
import java.util.*;
class Ex0
{
//-- a new type for points ---------//
public static class Point
{
public double x, y;
}
//-- main! -------------------------//
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// Read point A
Point A = new Point();
A.x = s.nextDouble();
A.y = s.nextDouble();
// Read point B
Point B = new Point();
B.x = s.nextDouble();
B.y = s.nextDouble();
// Compute midpoint M
Point M = new Point();
M.x = (A.x + B.x)/2;
M.y = (A.y + B.y)/2;
// Print results
System.out.print("midpoint of ");
System.out.print("(" + A.x + "," + A.y + ")");
System.out.print(" and ");
System.out.print("(" + B.x + "," + B.y + ")");
System.out.print(" is ");
System.out.println("(" + M.x + "," + M.y + ")");
}
}
import java.util.*;
class Ex1
{
public static class Point
{
public double x, y;
}
public static Point readPoint(Scanner s)
{
Point A = new Point();
A.x = s.nextDouble();
A.y = s.nextDouble();
return A;
}
public static String p2str(Point A)
{
return "(" + A.x + "," + A.y + ")";
}
public static Point mid(Point A, Point B)
{
Point M = new Point();
M.x = (A.x + B.x)/2;
M.y = (A.y + B.y)/2;
return M;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
Point A = readPoint(s);
Point B = readPoint(s);
System.out.println("midpoint of "
+ p2str(A) + " and "
+ p2str(B) + " is "
+ p2str(mid(A,B)));
}
}
Point
class inside of the Ex1 class, what's to stop us
from simply making the outside class Point?
Nothing! We get the same program doing the following:
import java.util.*;
public class Point
{
public double x, y;
public static Point readPoint(Scanner s)
{
Point A = new Point();
A.x = s.nextDouble();
A.y = s.nextDouble();
return A;
}
public static String p2str(Point A)
{
return "(" + A.x + "," + A.y + ")";
}
public static Point mid(Point A, Point B)
{
Point M = new Point();
M.x = (A.x + B.x)/2;
M.y = (A.y + B.y)/2;
return M;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
Point A = readPoint(s);
Point B = readPoint(s);
System.out.println("midpoint of "
+ p2str(A) + " and "
+ p2str(B) + " is "
+ p2str(mid(A,B)));
}
}
This seems a little strange, perhaps. But we really gain
something with this, because now, other class files can use
class Point.
import java.util.*;
class Ex2
{
public static double d(Point A, Point B)
{
double dx = A.x - B.x;
double dy = A.y - B.y;
return Math.sqrt(dx*dx + dy*dy);
}
public static void main(String[] args)
{
// Read 3 points
Scanner s = new Scanner(System.in);
Point A = Point.readPoint(s);
Point B = Point.readPoint(s);
Point C = Point.readPoint(s);
// Print triangle (use delta) and perimeter
System.out.println('\u0394' + Point.p2str(A)
+ "," + Point.p2str(B)
+ "," + Point.p2str(C));
System.out.println("Perimeter is " +
(d(A,B) + d(B,C) + d(C,A)));
}
}