Java 初学者 - 控制输出 - 生成 Asterix
我在完成该计划时遇到困难。我正在尝试制作一个程序来创建星号,然后将其变成三角形。
这就是我已经拥有的。
public class 12345 {
public static void main(String[] args) {
int n = 0;
int spaces = n;
int ast;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
for (int i = 0; i < n; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces)
System.out.print(' ');
else
System.out.print('*');
}
System.out.println();
spaces--;
}
}
}
它正在创建星号,但是我如何能够在它们形成三角形的地方继续它们...所以它们随着移动而变大,然后变小...
提前谢谢您!
I am having difficulties with completing this program. I am trying to make a program that creates asteriks, but then makes it into a triangle.
This is what I have already.
public class 12345 {
public static void main(String[] args) {
int n = 0;
int spaces = n;
int ast;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
for (int i = 0; i < n; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces)
System.out.print(' ');
else
System.out.print('*');
}
System.out.println();
spaces--;
}
}
}
It is creating the asteriks, but how would I be able to continue them where they make a triangle... so they get bigger as they go, and then back smaller...
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试移至
从标准输入读取
n
的值之后。这解决了你一半的问题,并希望让你走上正轨。
Try moving
to AFTER the value of
n
is read from stdin.This solves half your problem and hopefully gets you on the right track.
我在您的代码中添加了一些内容,并让它打印整个三角形,其中扫描仪中输入的数字将是底行中打印的星号数量。即如果输入为3,则三角形将是两行1->3;如果输入是 5,那么三角形将是 3 行 1->3->5,依此类推。
我在 if-else 之后添加了另一个 if 语句,当变量 j 超过第一个循环条件时触发。这会触发另一个循环,通过本质上重复您的第一个 if 语句来使输出线对称。
我希望这有帮助 =)
I added a few things to your code and got it to print the full triangle, where the number input in the scanner will be the number of asterisks printed in the bottom row. I.e. if the input is 3, the triangle will be two rows of 1->3; if the input is 5 then the triangle will be 3 rows of 1->3->5, and so on.
I added another if statement after your if-else that triggers when the variable j exceeds the first loop condition. This triggers another loop that makes the output lines symmetrical by essentially repeating your first if statement.
I hope this helps =)