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

最も簡単な方法:sidaを割り当てた後、に変更while-loopします。while(true)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

質問とは関係ありませんが、プログラミングをするときの最善の方法は、変数とコメントを英語で書くことです。

しかし、休憩は確かにそれを行うための最良の方法です. 0未満ではなく-1に等しいかどうかを確認しますが(これはLuigi Mendozaの回答への追加です)

if (sida == -1) {

それよりも

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

プログラムを終了するには、system.exit(0);を使用できます。

于 2013-02-28T18:48:11.617 に答える