Using Void Methods and Parameters

The following Java program uses Void method s and its Parameters.. I will be using the JCreator IDE in developing the program. To start in this tutorial, first open the JCreator IDE, click new and paste the following code.
  1. import java.util.*;
  2.  
  3. public class TriangleOfStars
  4. {
  5. static Scanner console = new Scanner(System.in);
  6.  
  7. public static void main (String[] args)
  8. {
  9. int numberOfLines;
  10. int counter;
  11. int numberOfBlanks;
  12.  
  13. System.out.println("Enter the number of star lines "
  14. + "(1 to 20) to be printed: ");
  15. numberOfLines = console.nextInt();
  16. System.out.println();
  17.  
  18. while (numberOfLines < 0 || numberOfLines > 20)
  19.  
  20. {
  21. System.out.println("The number of star lines "
  22. + "should between 1 and 20");
  23. System.out.print("Enter the number of star"
  24. + "lines (1 to 20) to ber printed: ");
  25. numberOfLines = console.nextInt();
  26. System.out.println();
  27.  
  28. }
  29. numberOfBlanks = 30;
  30.  
  31. for (counter = 1; counter <= numberOfLines;
  32. counter++)
  33. {
  34. printStars(numberOfBlanks, counter);
  35. numberOfBlanks--;
  36. }
  37. }
  38. public static void printStars(int blanks, int starsInLine)
  39. {
  40. int count;
  41.  
  42. for(count =1; count <= blanks; count++)
  43. System.out.print(" ");
  44. for(count =1; count <= starsInLine; count++)
  45. System.out.print(" *");
  46. System.out.println();
  47. }
  48. }
Sample Run: The program works as follows: The statement  printStars(numberOfBlanks, counter); in the method main is a method call. The method printStars has two parameters. Whenever the method executes, it outputs a line of stars with a certain number of blanks before the stars. The number of blanks and the number of stars in the line are passed as parameters to the method printStars. The first paramenter, blanks, tells how many blanks to print, second parameter, starsInLin, tells how many stars to print in the line. In the method main, the user is first asked to specify how many lines of stars to print.
  1. System.out.println("Enter the number of star lines "
  2. + "(1 to 20) to be printed: ");
The statement
  1. while (numberOfLines < 0 || numberOfLines > 20)
  2.  
  3. {
  4. System.out.println("The number of star lines "
  5. + "should between 1 and 20");
  6. System.out.print("Enter the number of star"
  7. + "lines (1 to 20) to ber printed: ");
  8. numberOfLines = console.nextInt();
  9. System.out.println();
Ensures that the program prints the triangular grid of stars only if the number of lines between 1 and 20. The statement
  1. for (counter = 1; counter <= numberOfLines;
  2. counter++)
in the method main calls the method printStars

Add new comment