Please write a tree with red leaves and black branches in Java language.
时间: 2023-09-18 14:05:31 浏览: 128
### 回答1:
我不熟悉Java语言,不过我可以试着用Java描述一棵树:Tree tree = new Tree("Red Leaves", "Black Branches");
tree.addLeaves("Red Leaves");
tree.addBranches("Black Branches");
### 回答2:
可以使用Java语言编写带有红叶和黑色树干的树。以下是实现此功能的示例代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RedLeafBlackBranchTree extends JPanel {
private static final long serialVersionUID = 1L;
private final int WIDTH = 800;
private final int HEIGHT = 800;
public RedLeafBlackBranchTree() {
setBackground(Color.WHITE);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawTree(g, WIDTH / 2, HEIGHT - 50, 100, -90);
}
private void drawTree(Graphics g, int x1, int y1, double length, double angle) {
if (length < 10) {
return;
}
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * length);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * length);
g.setColor(Color.BLACK);
g.drawLine(x1, y1, x2, y2);
drawTree(g, x2, y2, length * 0.7, angle - 30);
drawTree(g, x2, y2, length * 0.7, angle + 30);
for (int i = 0; i < 15; i++) {
g.setColor(Color.RED);
g.fillOval(x2 - 8, y2 - 8, 16, 16);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Red Leaf Black Branch Tree");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 800);
frame.add(new RedLeafBlackBranchTree());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
运行该程序,将显示一个具有红叶和黑色树枝的树。
### 回答3:
public class Tree {
public static void main(String[] args) {
drawTree();
}
private static void drawTree() {
String trunk = "BBBBBBBBBBB";
String branch = "BBBBBBBB";
String leaves = "RRR";
for (int i = 0; i < 4; i++) {
System.out.printf("%" + (11 - i) + "s\n", trunk);
}
for (int i = 0; i < 4; i++) {
System.out.printf("%" + (11 - i) + "s\n", branch);
}
for (int i = 0; i < 3; i++) {
System.out.printf("%" + (12 - i) + "s\n", leaves);
}
}
}
这段代码使用Java语言绘制一棵有红叶子和黑树枝的树。树干使用字符串"BBBBBBBBBBB"表示,树枝使用字符串"BBBBBBBB"表示,树叶使用字符串"RRR"表示。通过循环打印字符串,树的形状就被打印出来。树干共有4层,树枝共有4层,树叶共有3层。具体绘制过程是通过循环控制字符串的右对齐输出。输出结果就是一棵有红叶子和黑树枝的树的形状。