我想用Java写一个捕捉用户整数(假设数据有效)的程序,然后根据整数的大小输出菱形形状,即用户输入5,输出将是:使用循环的Java ascii艺术
--*--
-*-*-
*---*
-*-*-
--*--
到目前为止,我有:
if (sqr < 0) {
// Negative
System.out.print("#Sides of square must be positive");
}
if (sqr % 2 == 0) {
// Even
System.out.print("#Size (" + sqr + ") invalid must be odd");
} else {
// Odd
h = (sqr - 1)/2; // Calculates the halfway point of the square
// System.out.println();
for (j=0;j<sqr;j++) {
for (i=0;i<sqr;i++) {
if (i != h) {
System.out.print(x);
} else {
System.out.print(y);
}
}
System.out.println();
}
}
刚刚输出
--*--
--*--
--*--
--*--
--*--
任何ID eas,我在考虑减少h
的价值,但那只会产生钻石的左手边。
您能否向我解释一下Math.abs()函数的作用,我是否认为它给出了任何数字的正值?我已经向您的代码添加了评论,以表明我明白发生了什么。 – Mike
你说得对,迈克,这正是它所做的。 –