3

我不明白我应该如何让这个程序停止。基本上它想要我做的是当我输入 -1 时程序关闭。我只是不知道怎么做。哦!“sida”在瑞典语中的意思是边。不知道有没有用!在这里得到你们的帮助会很棒!

import java.util.Scanner;
public class triangle
{

//Triangle is going up
public static void triangelUpp(int sida)
{

    for(int i = 0; i <= sida; i++)
    {
        for(int j = 1; j <= i; j++)
        System.out.print("*");
        System.out.println();
    }       
}


//Triangle going down
public static void triangelNed(int sida)
{

    for(int i = 0; i <= sida; i++)
    {
        for(int j = 1; j <= sida - i; j++)
        System.out.print("*");
        System.out.println();
    }       
}


public static void main(String[] args)
{

    //Variables 
    Scanner keyboard = new Scanner(System.in);
    int vinkel = 0;
    int sida = 0;


    //Rules
    while(sida !=-1)
    {
        if(vinkel == 0)
            triangelNed(sida);

        else if(vinkel == 1)
            triangelUpp(sida);

    System.out.println("Write the length of the triangle and end with -1");
    sida = keyboard.nextInt();

    System.out.println("Is the angle going to be up(1) or down?(0)");
    vinkel = keyboard.nextInt();

    }

}

}
4

3 回答 3

4

最简单的方法:更改while-looptowhile(true)然后在分配 sida 之后:if (sida < 0) { break; }

换句话说:

while(true) {
    //some logic here...
    sida = keyboard.nextInt();
    //if (sida < 0) {
    //since you don't like the regular approach, changing it to fit your odd needs
    if (sida == -1) {
        //breaks the while loop
        break;
    }
    //rest of code...
}

使用System.exit(0)只会终止进程,显示示例

while(true) {
    //code here...
    //same here
    //if (sida < 0) {
    if (sida == -1) {
        //comment/uncomment the options to see the program behavior
        //using this, the message after the while loop will be printed
        break;
        //using this, the message after the while loop won't be printed
        //System.exit(0);
    }
}
System.out.println("Thanks! See ya later");
于 2013-02-28T18:53:49.240 回答
0

与问题无关,编程时最好的办法是用英文写你的变量和注释。

但是break确实是最好的方法。虽然我会检查它是否等于 -1 而不是小于 0。(这是对 Luigi Mendoza 的回答的补充)

if (sida == -1) {

而不是

if (sida < 0) {
于 2013-02-28T19:07:21.290 回答
-1

要退出程序,您可以使用 system.exit(0);

于 2013-02-28T18:48:11.617 回答