题干
编写二维平面上的点(Point)类,具体内容包括:
(1) 两个私有的double类型的数据域,分别表示点的x和y坐标;
(2) 两个数据域的修改器(set方法)和读取器(get方法);
(3) 一个计算当前点和另一个点之间的距离的方法:
public double distance(Point p)
提示:使用Math类的sqrt()方法进行平方根运算。
【试题输入输出】
编写测试类,创建两个Point对象,从键盘输入两个点的x和y坐标,并计算两个点之间的距离,样例如下:
代码如下
import java.util.Scanner;
public class Point {
public static void main(String[] args)
{
double x1, x2, y1, y2;
Scanner sc = new Scanner(System.in);
x1 = sc.nextDouble();
y1 = sc.nextDouble();
x2 = sc.nextDouble();
y2 = sc.nextDouble();
sc.close();
MyPoint p1 = new MyPoint(x1, y1), p2 = new MyPoint(x2, y2);
System.out.println("两点距离为" + String.format("%.2f", p1.getD(p2)));
}
}
class MyPoint
{
private double x, y;
public MyPoint(double x, double y)
{
this.x = x;
this.y = y;
}
public MyPoint()
{
this(0, 0);
}
public double getD(MyPoint p)
{
return Math.sqrt ((this.x - p.x) * (this.x - p.x) +
(this.y - p.y) * (this.y - p.y));
}
}
问题
[1]String.format
String.format
是一个静态方法,用于格式化字符串输出。它允许您按照指定的格式将各种类型的数据转换为字符串,然后返回格式化后的字符串。
String.format
的常用语法如下:
String formattedString = String.format(format, arguments);
其中:
-
format
是一个格式字符串,它指定了输出的格式。例如,"%.2f"
表示保留两位小数的浮点数,"%d"
表示整数,"%s"
表示字符串等等。您可以根据需要选择合适的格式。 -
arguments
是要格式化的参数,可以是一个或多个,根据格式字符串中的占位符数量来确定。例如,如果格式字符串中有一个%f
,那么需要提供一个浮点数作为参数。如果格式字符串中有两个%s
,那么需要提供两个字符串作为参数。
String.format
方法会根据格式字符串将参数转换为指定格式,然后返回一个格式化后的字符串。
示例:
double num = 3.1415926;
String formattedString = String.format("%.2f", num);
System.out.println(formattedString); // 输出结果为 "3.14"
在上面的示例中,String.format("%.2f", num)
将浮点数 num
格式化为保留两位小数的字符串,并返回结果 "3.14"
。
[2]计算两点之间的距离——>计算当前点和已知点的距离
return Math.sqrt((this.x - p.x)*(this.x - p.x)+(this.y - p.y) * ((this.y - p.y)));