三角形程序java,java打印一个三角形

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.

For example

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();

}

}

}

}

}

}

解决方案

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.

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.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值