Tutorial Programming dan Informasi Teknologi

January 17, 2017

Tutorial Membuat Pola Ular dengan Looping

Output

 /**  
  *   
  */  
 package latihan;  
 import java.util.Scanner;  
 /**  
  * Created by Muhamad Huda Avianto Jan 14, 2017  
  */  
 public class LatihanFor1 {  
      public static void main(String[] args) {  
           Scanner scan = new Scanner(System.in);  
           System.out.println("masukan nilai : ");  
           int nilai = scan.nextInt();  
           LatihanFor1 ax = new LatihanFor1();  
           ax.pola(nilai);  
      }  
      public void pola(int n) {  
           for (int i = 0; i < n - 1; i++) {  
                for (int j = 0; j < n; j++) {  
                     if (i % 2 == 0) {  
                          System.out.print("*");  
                     } else if (i % 4 == 1 && j == n - 1) {  
                          System.out.print("*");  
                     } else if (i % 4 == 3 && j == 0) {  
                          System.out.print("*");  
                     } else {  
                          System.out.print(" ");  
                     }  
                }  
                System.out.println();  
           }  
      }  
 }  

2 comments:

  1. Too complicated. This can be done in a single loop.

    In C# (for padding in Java you can use StringUtils leftPad/rightPad)

    public static void Pola(int n)
    {
    string x = "".PadLeft(n, '*');
    string l = "*".PadLeft(n - 1, ' ');
    string r = "*".PadRight(n - 1, ' ');
    bool y = true;

    for (int i = 0; i < n; i++)
    {
    if (i % 2 == 0){
    Console.WriteLine(x);
    }
    else
    {
    if (y)
    {
    Console.WriteLine(l);
    y = false;
    }
    else {
    Console.WriteLine(r);
    y = true;
    }
    }
    }
    }

    ReplyDelete
    Replies
    1. Your feedback is very useful and can be used as another reference.

      thx for your visit.

      Delete

Contact Form

Name

Email *

Message *