Java OCA OCP Practice Question 2165

Question

Given the following code:

public class Main {
  public static void main(String[] args) {
    System.out.format("|");
    // (1) INSERT LOOP HERE
    System.out.format("%n");
  }
}

Which loops, when inserted at (1), will result in the program printing:

| t|  tr|   tru|    true|

Select the three correct answers.

(a) for (int i = 1; i < 5; i++) {
      System.out.format("%" + i*2 + "." + i + "b|", 2007);
    }//from   w ww  .  j a v a2 s  .c  o m
(b) for (int i = 0; i < 5; i++) {
      System.out.format("%" + (i==0 ? "" : i*2) + "." + i + "b|", 2007);
    }
(c) for (int i = 0; i < 4; i++) {
      System.out.format("%" + (i+1)*2 + "." + i + "b|", 2007);
    }
(d) for (int i = 0; i < 4; i++) {
      System.out.format("%" + (i+1)*2 + "." + (i+1) + "b|", 2007);
    }
(e) for (int i = 4; i > 0; i--) {
      System.out.format("%" + (5-i)*2 + "." + (5-i) + "b|", 2007);
    }


(a), (d), and (e)

Note

All the loops format the value true.

(a), (d), and (e) use the format strings %2.1b, %4.2b, %6.3b, and %8.4b, resulting in the output:

| t|  tr|   tru|    true|

(b) uses the format strings %.0b, %2.1b, %4.2b, %6.3b, and %8.4b, resulting in the output:

|| t|  tr|   tru|    true|

(c) uses the format strings %2.0b, %4.1b, %6.2b, and %8.3b, resulting in the output:

|  |   t|    tr|     tru|



PreviousNext

Related