【CS61B】 课后练习 HW 0: A Java Crash Course


Exercise 1a: Drawing a Triangle

public class TriangleDrawer {
   public static void main(String[] args) {
      int i=1;
      while(i<=5){
        int cnt=i;
        while(cnt>0){
          System.out.print('*');
          cnt--;          
        }
        System.out.println();
         i++;
      }
   }
}

Exercise 1b: DrawTriangle

public class TriangleDrawer {
   public static void drawTriangle(int N) {
      int i=1;
      
      while(N>0){
         int cnt=i;
         while(cnt>0){
          System.out.print('*');
            cnt--;
         }
        System.out.println();
         N--;
         i++;
      }
   }
   public static void main(String[] args) {
      drawTriangle(5);
   }
}

Excercise2

public class ClassNameHere {
   public static int max(int[] m) {
      int len=m.length;
      int max=0;
      int i=0;
      while (i<len){
         if(m[i]>max){
            max=m[i];
         }
         i++;
      }
       return max;
   }
   public static void main(String[] args) {
      int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6};   
      System.out.print(max(numbers));
   }
}

Exercise 3

public class ClassNameHere {
   public static int max(int[] m) {
      int len=m.length;
      int max=0;
      for(int i=0;i<len;i++)
      {
         if(m[i]>max){
            max=m[i];
         }  
      }
       return max;
   }
   public static void main(String[] args) {
      int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6};   
      System.out.print(max(numbers));
   }
}

Exercise 4

public class BreakContinue {
  public static void windowPosSum(int[] a, int n) {
    /** your code here */ 
    for(int i=0;i<a.length;i++){
      if(a[i]<0) continue;
      for(int j=i+1;j<=i+n;j++){
        if(j>=a.length) break;
        a[i]+=a[j];
      }
    }
  }

  public static void main(String[] args) {
    int[] a = {1, 2, -3, 4, 5, 4};
    int n = 3;
    windowPosSum(a, n);

    // Should print 4, 8, -3, 13, 9, 4
    System.out.println(java.util.Arrays.toString(a));
  }
}