我不明白我该如何让这个程序停止。基本上它要我做的是当我输入-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();
}
}
}
答案 0 :(得分:4)
最简单的方法:将while-loop
更改为while(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");
答案 1 :(得分:0)
与问题无关,编程时最好的办法是用英语编写变量和注释。
但休息确实是最好的方法。虽然我会检查它是否等于-1而不是小于0.(这是Luigi Mendoza答案的补充)
if (sida == -1) {
而不是
if (sida < 0) {
答案 2 :(得分:-1)
退出您可以使用的程序 system.exit(0);