- Create a new class namedĀ EncapGen and add the following code to main so the class appears as follows.
public class EncapGen { public static void main(String[] args){ int i = 1; while (i <= 6){ System.out.printf("%4d",2*i); i=i+1; } System.out.println(); } }
- Compile and run the program.
$ javac EncapGen.java $ java EncapGen 2 4 6 8 10 12
- Add a new method called printRow and move the code from main to printRow.
public class EncapGen { public static void main(String[] args){ printRow(); } public static void printRow(){ int i = 1; while (i <= 6){ System.out.printf("%4d",2*i); i=i+1; } System.out.println(); } }
- Compile and run the program and the results are the same.
- Modify printRow so that it takes an integer as a parameter.
- Change the numeral two in the printf statement to the variable name passed to printRow as a parameter.
- Change the call to printRow in main to pass the numeral 2 as the argument. The class should now appear as follows.
public class EncapGen { public static void main(String[] args){ printRow(2); } public static void printRow(int n){ int i = 1; while (i <= 6){ System.out.printf("%4d",n*i); i=i+1; } System.out.println(); } }
- Compile and run the program and the results are the same.
$ javac EncapGen.java $ java EncapGen 2 4 6 8 10 12