Added Java lab programs

This commit is contained in:
2025-12-17 16:36:20 +05:30
parent ac2904f5db
commit 2f4beade3b
46 changed files with 882 additions and 0 deletions
Binary file not shown.
+53
View File
@@ -0,0 +1,53 @@
class MyPoint {
private int x;
private int y;
// No-argument constructor
MyPoint() {
x = 0;
y = 0;
}
// Overloaded constructor
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
// Set both x and y
void setXY(int x, int y) {
this.x = x;
this.y = y;
}
// Return x and y as a 2-element array
int[] getXY() {
return new int[] { x, y };
}
// String representation
public String toString() {
return "(" + x + ", " + y + ")";
}
// Distance to given (x, y)
double distance(int x, int y) {
return Math.sqrt(
(this.x - x) * (this.x - x) + (this.y - y) * (this.y - y)
);
}
// Distance to another MyPoint object
double distance(MyPoint another) {
return Math.sqrt(
(this.x - another.x) * (this.x - another.x) +
(this.y - another.y) * (this.y - another.y)
);
}
// Distance to origin (0, 0)
double distance() {
return Math.sqrt(x * x + y * y);
}
}
Binary file not shown.
+57
View File
@@ -0,0 +1,57 @@
import java.util.Scanner;
public class TestMyPoint {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Test default constructor
MyPoint p1 = new MyPoint();
System.out.println("p1: " + p1);
// Test overloaded constructor
System.out.print("Enter x coordinate: ");
int x = sc.nextInt();
System.out.print("Enter y coordinate: ");
int y = sc.nextInt();
MyPoint p2 = new MyPoint(x, y);
System.out.println("p2: " + p2);
// Test setXY()
System.out.print("Enter new x for p1: ");
int x1 = sc.nextInt();
System.out.print("Enter new y for p1: ");
int y1 = sc.nextInt();
p1.setXY(x1, y1);
System.out.println("Updated p1: " + p1);
// Test getXY()
int[] coords = p1.getXY();
System.out.println("getXY(): (" + coords[0] + ", " + coords[1] + ")");
// Test distance() to origin
System.out.println("Distance from p1 to origin: " + p1.distance());
// Test distance(int x, int y)
System.out.print("Enter x of another point: ");
int x2 = sc.nextInt();
System.out.print("Enter y of another point: ");
int y2 = sc.nextInt();
System.out.println(
"Distance from p1 to (" +
x2 +
", " +
y2 +
"): " +
p1.distance(x2, y2)
);
// Test distance(MyPoint another)
System.out.println("Distance from p1 to p2: " + p1.distance(p2));
sc.close();
}
}