用java绘制不相交的圆圈,个数可以从键盘上输入,半径在10-20之间。(需要用数组存放圆圈)
时间: 2024-05-19 09:14:39 浏览: 14
以下是使用Java绘制不相交圆圈的代码示例:
import java.awt.*;
import java.util.Scanner;
public class DrawCircles {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入圆圈的个数:");
int n = scanner.nextInt(); // 从键盘读取圆圈个数
Circle[] circles = new Circle[n]; // 定义一个圆圈数组
// 随机生成圆圈的位置和半径
for (int i = 0; i < n; i++) {
int x = (int) (Math.random() * 400); // 生成0-400之间的随机数
int y = (int) (Math.random() * 400); // 生成0-400之间的随机数
int r = (int) (Math.random() * 10) + 10; // 生成10-20之间的随机数
circles[i] = new Circle(x, y, r); // 创建一个圆圈对象
}
// 判断圆圈是否相交
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (circles[i].isIntersect(circles[j])) { // 判断圆圈是否相交
System.out.println("圆圈" + (i+1) + "和圆圈" + (j+1) + "相交了!");
}
}
}
// 绘制圆圈
DrawPanel panel = new DrawPanel(circles);
JFrame frame = new JFrame("Draw Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.add(panel);
frame.setVisible(true);
}
}
class Circle {
private int x;
private int y;
private int r;
public Circle(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}
// 判断圆圈是否相交
public boolean isIntersect(Circle c) {
int dx = this.x - c.x; // 圆心横坐标之差
int dy = this.y - c.y; // 圆心纵坐标之差
int d = (int) Math.sqrt(dx * dx + dy * dy); // 圆心距离
return (d < this.r + c.r); // 如果圆心距离小于两个圆圈半径之和,则相交
}
// 绘制圆圈
public void draw(Graphics g) {
g.drawOval(x-r, y-r, r*2, r*2);
}
}
class DrawPanel extends JPanel {
private Circle[] circles;
public DrawPanel(Circle[] circles) {
this.circles = circles;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘制圆圈
for (Circle c : circles) {
c.draw(g);
}
}
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)