java打印三角形
我正在尝试制作一个程序,需要用户输入三角形的长度和方向。我遇到的问题是,在我运行程序后,它会不断向程序中添加更多的数字 比如说java打印三角形,java,user-input,Java,User Input,我正在尝试制作一个程序,需要用户输入三角形的长度和方向。我遇到的问题是,在我运行程序后,它会不断向程序中添加更多的数字 比如说 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 * ** *** ****
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();
}
}
}
}
}
}
import java.util.Scanner;
公共类三角形{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
//初始变量för三角形IDA。
双倍长度=0;
双边长度=0;
//此部分将要求用户输入
系统输出
.打印(“说明两面的长度(以-1结尾):”;
while(边长!=-1){
//输入。
边长=in.nextDouble();
如果(边长!=-1){
//输入将以可变长度保存。
长度+=边长;
//这部分将要求用户说明三角形是否正确
//向上或向下。
系统输出
.打印(“三角形是朝下(0)还是朝上(1):”;
字符串方向=in.next();
//如果变量方向等于(1),则该部分将
//跑。
如果(方向等于(“1”)){
对于(int i=1;i您有length+=sideLength
。这将继续为while循环的每个周期向length
变量添加sideLength
输入。您可能只需要length=sideLength
要让它在每次迭代中再次打印出您的第一个提示,只需将您的System.out.print(“声明两侧的长度(以-1结尾):”);
调用放入while循环中。(它也需要位于sideLength=in.nextDouble();
之前,以便在输入之前显示提示。)谢谢您的帮助:)