gpt4 book ai didi

java - 菜鸟需要帮助如何退出我的 Java 程序

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:53:27 34 4
gpt4 key购买 nike

我不明白我应该如何让这个程序停止。基本上它要我做的是当我输入 -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();

}

}

}

最佳答案

最简单的方法:更改 while-loopwhile(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");

关于java - 菜鸟需要帮助如何退出我的 Java 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143246/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com