简体   繁体   中英

How do I get my program to state an error and exit if input is < 1

So this program just prints a basic centered triangle. The user inputs how many lines they want the triangle to have in it. I'm just not sure how to insert an error message and exit the program with in this. What would be the best way to do it without disrupting anything?

import java.util.Scanner;

public class 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
    }

}

}

After

int numLines = input.nextInt();

you add

if (numlines <= 0)
   return;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM