Name_______________________________ Your final answer to each question should appear on this sheet.
v22.0101, practice Exam
For the String problems, you may use the charAt(j) and length() methods.
None of the methods you write should read from the console
or write to the screen. Don't call System.out
1a.Given the following class fragment
private int number;
private boolean perfect;
public Test(int num)
number = num;
write a method for the Test class with the heading public void isPerfect()
that determines if number is a perfect number. If it is, perfect
is set to true else to false.
Then write a method with the heading public boolean getPerfect()
that returns the value of perfect.
The sum of all the divisors of a perfect number
except the number itself equals the number. Thus 6 is a perfect number since 1 + 2 + 3 equals 6.
So if number were 6, perfect would be true.
1b. Write the part of the main method code to instantiate an object one
of class Test so that number would be
set to 6, and an object two so that number
would be set to 11. Then write the code to execute isPerfect()
and getPerfect() for both objects.
2.Write a static method public static int numWords(String s)that returns
the number of words in a string that is the parameter s. A word is a group
of non-blank characters sandwiched between the first quote and a blank, or two blanks,
or a blank and the final quote. More than one blank may separate words.
For example in "abcd____efg___hij_lkm", there are four words. The "_" represents a blank.
Assume the first and last characters in the string are non-blanks.
Hint: for all but the last word, when does a word end?
Use a for loop.
3.. Write a static method public static int numNonDivisors(int n) that
the number of non-divisors that n has. If n is 8, the non-divisors
are 3, 5, 6, and 7. Thus 8 has four non-divisors.
4. Write a static method public static String generate(int n)
that returns the String formed from the concatenation of the first
n sequential integers, 1, 2, 3, 4, ...n, with the following proviso.
The first time the integer is divisible by 10, the letter A replaces
that integer and is concatenated with the string. Every other time the integer
is divisible by 10, the next letter of the alphabet is concatenated with the
string, Thus if n is 21, the method should return the string