Java Reference
In-Depth Information
2. Write a method called writeNums that takes an integer n as a parameter and prints to the console the first n integers
starting with 1 in sequential order, separated by commas. For example, consider the following calls:
writeNums(5);
System.out.println(); // to complete the line of output
writeNums(12);
System.out.println(); // to complete the line of output
These calls should produce the following output:
1, 2, 3, 4, 5
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Your method should throw an IllegalArgumentException if passed a value less than 1 .
3. Write a method called writeSequence that accepts an integer n as a parameter and prints to the console a symmet-
ric sequence of n numbers composed of descending integers that ends in 1, followed by a sequence of ascending
integers that begins with 1. The following table indicates the output that should be produced for various values of n :
Method call Output produced
-----------------------------------------
writeSequence(1); 1
writeSequence(2); 1 1
writeSequence(3); 2 1 2
writeSequence(4); 2 1 1 2
writeSequence(5); 3 2 1 2 3
writeSequence(6); 3 2 1 1 2 3
writeSequence(7); 4 3 2 1 2 3 4
writeSequence(8); 4 3 2 1 1 2 3 4
writeSequence(9); 5 4 3 2 1 2 3 4 5
writeSequence(10); 5 4 3 2 1 1 2 3 4 5
Notice that when n is odd the sequence has a single 1 in the middle, while for even values it has two 1s in the
middle. Your method should throw an IllegalArgumentException if it is passed a value less than 1 .
4. Write a recursive method called doubleDigits that accepts an integer n as a parameter and returns the integer
obtained by replacing every digit of n with two of that digit. For example, doubleDigits(348) should return
334488 . The call doubleDigits(0) should return 0 . Calling doubleDigits on a negative number should return
the negation of calling doubleDigits on the corresponding positive number; for example, doubleDigits(-789)
should return -778899 .
5. Write a recursive method called writeBinary that accepts an integer as a parameter and writes its binary represen-
tation to the console. For example, writeBinary(44) should print 101100 .
6. Write a recursive method called writeSquares that accepts an integer parameter n and prints the first n squares
separated by commas, with the odd squares in descending order followed by the even squares in ascending order. For
example, writeSquares(8); prints the following output:
49, 25, 9, 1, 4, 16, 36, 64
Search WWH ::




Custom Search