问题描述
我正在尝试创建一个程序,用户输入三角形应该多长时间以及它的方向。我遇到的问题是它在运行后不断向程序添加更多数字。
I'm trying to make a program that takes user input such how long should the triangle be and its direction. The problem I have is that it keeps adding more numbers to the program after I run it.
例如
State the length of the two sides (finish with -1): 5
Should the triangle face down (0) or up(1): 1
*
**
***
****
*****
2
Should the triangle face down (0) or up(1): 1
*
**
***
****
*****
******
*******
我的代码:
import java.util.Scanner;
public class Triangel {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Initierings variabler för triangelsida.
double length = 0;
double sideLength = 0;
// This part will ask for user input
System.out
.print("State the length of the two sides (finish with -1): ");
while (sideLength != -1) {
// Input.
sideLength = in.nextDouble();
if (sideLength != -1) {
// Input will be saved in variable length.
length += sideLength;
// This part will ask the user to state whether the triangle is
// up or down.
System.out
.print("Should the triangle face down (0) or up(1): ");
String direction = in.next();
// if the variables direction is equal to (1) this part will
// run.
if (direction.equals("1")) {
for (int i = 1; i <= ((int) (length)); i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
// if direction equals to (0) .
else {
for (int i = 1; i <= ((int) (length)); i++) {
for (int j = ((int) (length)); j >= 1; j--) {
if (j >= i)
System.out.print("*");
}
System.out.println();
}
}
}
}
}
}
推荐答案
你有长度+ = sideLength
。这将继续为while循环的每个循环添加 sideLength
输入到 length
变量。你可能想要的只是 length = sideLength
。
You have length += sideLength
. This will keep adding the sideLength
input to the length
variable for each cycle of the while loop. What you probably want instead is just length = sideLength
.
要让它在每次迭代时再次打印出你的第一个提示,只需输入你的 System.out.print(说明两者的长度) sides(以-1结束):);
在while循环中调用。 (它需要在 sideLength = in.nextDouble();
之前,以便在输入输入之前显示提示。)
To make it print out your first prompt again on each iteration, simply put your System.out.print("State the length of the two sides (finish with -1): ");
call inside your while loop. (It needs to come before sideLength = in.nextDouble();
as well so that the prompt is displayed before input is entered.)
这篇关于java打印一个三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!