我正在尝试制作一个程序,该程序接受用户输入,例如三角形应该有多长及其方向。我遇到的问题是,在我运行程序后,它不断向程序添加更多数字。
例如
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
*
**
***
****
*****
******
*******
My code:
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();
}
}
}
}
}
}
你有length += sideLength
。这将不断添加sideLength
输入到length
while 循环的每个循环的变量。你可能想要的只是length = sideLength
.
要使其在每次迭代时再次打印出您的第一个提示,只需将您的System.out.print("State the length of the two sides (finish with -1): ");
在 while 循环内调用。 (它需要先于sideLength = in.nextDouble();
以及显示提示before输入已输入。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)