java基于用户输入以ASCIIart样式绘制心脏
我有个问题,希望你能帮我解决
Java程序应该根据用户给出的输入N
以ASCII艺术风格打印心形
信息:
- 要打印的字符:♡ ♥ 李>
- 可以分别打印心脏的顶部和底部部分李>
- 解决方案必须基于for循环李>
N
决定心脏的顶部:- 顶部倾斜的外侧有
N
颗心 - 顶部的扁平部分有
N
个心形 - 两个扁平零件之间的间隙为
N
宽
- 顶部倾斜的外侧有
示例:
我的当前代码:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of hearts you want to print");
int userInput = scan.nextInt();
printTop(userInput);
}
public static void printTop(int userInput) {
String row = "";
int width = 2 * (userInput - 1) + 3 * userInput;
for (int height = 0; height < userInput; height++) {
for (int i = 0; i < userInput - 1; i++) {
row += "♡";
}
for (int i = 0; i < userInput; i++) {
row += "♥";
}
for (int i = 0; i < userInput; i++) {
row += "♡";
}
for (int i = 0; i < userInput; i++) {
row += "♥";
}
for (int i = 0; i < userInput - 1; i++) {
row += "♡";
}
row += "\n";
}
System.out.println(row);
}
想法:
- 心脏的第一行是基于:
2 * (userInput - 1) + 3 * userInput
- 每行的彩色心形必须增加2李>
- 每行中心心脏必须减少2李>
- 侧面的透明心脏必须每行减少1李>
问题:
- 我怎样才能让不同类型的心脏在每一条线上完成他们的“工作”李>
# 1 楼答案
画一个ASCII艺术心形,充满和空
想象一个坐标平面,画一个由两个半圆形和一个半菱形组成的图形
图1和图2:
图1-Try it online!
产出1:
图2-Try it online!
产出2:
另请参见:
•Print out an ASCII circle and axes with characters
•How to draw a double empty ASCII rhombus?
# 2 楼答案
我用以下代码解决了这个任务:
# 3 楼答案
您可以使用
java.awt
包将这些字符♥♡
绘制为黑白图片:然后你可以打印一个2D像素阵列作为组成这张图片的字符:
Try it online!
# 4 楼答案
最简单的方法是为线条构建一个
char[]
,用空白的心填充,然后用白色的心填充侧面,然后计算并用白色的心填充中心结果是非常简洁和快速的代码,但中心计算可能看起来很复杂,尽管它是一个简单的公式
请注意,代码不需要单独的部分来打印上半部分和下半部分。这是通过将
i
从负数迭代到正数来实现的技巧,例如,对于n=4
,i
从-3
迭代到+8
,两者都包括在内测试
由于我浏览器上的字体没有使用等宽的字体,结果很糟糕,所以下面的测试使用常规字符
输出
# 5 楼答案
不错的挑战:
在我的输出中,它不是一个完美的矩形,因为白色的心比彩色的心小一点