Chapter:Classes - Commenting code - Exercises

From Juneday education
Jump to: navigation, search

Exercises on commenting code

Q1

Create a file like the one below (note that the file is in a package and you need to create (and use) a corresponding directory structure).

 
package org.commenteers;

public class Simple {

  public static void main(String[] args) {
    System.out.println("Simple class to test comments");

    for (int i = 0; i < 10; i++) {
      System.out.println("  i: " + i);
    }
  }

}

Expand using link to the right to see a suggested solution/answer.

Just create it in the correct directory structure!

Q2

Write a comment before the main method saying "This is the main method".

Expand using link to the right to see a suggested solution/answer.

Suggestion:

 
package org.commenteers;

public class Simple {

  // This is the main method
  public static void main(String[] args) {
    System.out.println("Simple class to test comments");

    for (int i = 0; i < 10; i++) {
      System.out.println("  i: " + i);
    }
  }
}

Q3

Change the class so that the first println statement is ignored by the compiler. Use single line comment to achieve this.

Expand using link to the right to see a suggested solution/answer.

Suggestion:

 
package org.commenteers;

public class Simple {

  // This is the main method
  public static void main(String[] args) {
    //System.out.println("Simple class to test comments");

    for (int i = 0; i < 10; i++) {
      System.out.println("  i: " + i);
    }
  }
}

Q4

Write an introduction text to the class using multi line comments.

Expand using link to the right to see a suggested solution/answer.

Suggestion:

 
package org.commenteers;

/*
 *
 * This class is something the authors forced us to work with
 * The class really does nothing useful and all we'll ever get
 * out of it is how to comment things... but, hey that's kind of useful!
*/

public class Simple {

  // This is the main method
  public static void main(String[] args) {
    //System.out.println("Simple class to test comments");

    for (int i = 0; i < 10; i++) {
      System.out.println("  i: " + i);
    }
  }
}

Q5

Change the class so that the for loop is not executed (enclose it in a multi line comment)

Expand using link to the right to see a suggested solution/answer.

Suggestion:

 
package org.commenteers;

/*
 *
 * This class is something the authors forced us to work with
 * The class really does nothing useful and all we'll ever get
 * out of it is how to comment things... but, hey that's kind of useful!
*/

public class Simple{

  // This is the main method
  public static void main(String[] args) {
    //System.out.println("Simple class to test comments");

    /*
    for (int i = 0; i < 10; i++) {
      System.out.println("  i: " + i);
    }
    */
  }
}

Links

Further reading

Where to go next

Next page is: Classes_-_Declaring_variables

« PreviousBook TOCNext »