如何输入<1,如何让我的程序声明错误并退出

问题描述 投票:0回答:1

所以这个程序只打印一个基本的居中三角形。用户输入他们希望三角形中有多少行。我只是不确定如何插入错误消息并退出程序。在不破坏任何事情的情况下,最好的方法是什么?

import java.util.Scanner;

公共类Triangle {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.print("Enter the number of lines: ");
    Scanner input = new Scanner(System.in);
    int numLines = input.nextInt();

    for (int i = 0; i < numLines; i++)
    {
        for (int j = 0; j <= numLines - i; j++)
        {
            System.out.print(" "); //prints the proper number of spaces so that it's centered
        }

        for (int k = 0; k <= 2*i; k++)
        {
            System.out.print("*"); //prints proper number of *
        }

        System.out.println(); //makes new row
    }

}

}

java loops for-loop exit
1个回答
1
投票

int numLines = input.nextInt();

你添加

if (numlines <= 0)
   return;
© www.soinside.com 2019 - 2024. All rights reserved.