I Hate CBT's

View Original

7.6.12 Phonebook

Question: Write a program that asks the user for a number of days, and calculates how much money they
would earn over that many days if their salary were one penny the first day, two pennies the second
day, four pennies the third day, and so on, doubling each day. Your program should display a (nicely
formatted!) table showing the salary for each day, as well as the total pay for the number of days
specified by the user. The output should be displayed in dollar amounts, not the number of pennies.
Input validation: Do not accept a number less than 1 for the number of days worked.
Answer: for (int i = 0; i < days; days--)//change to days++
sum+=i;//add
cout << days << "\t\t" << (sum+=days) << endl;//revise to
cout<<"The sum of integers 0 to "<<days<<" is "<<sum<<endl;
==================================================
Question: Write a for loop that calculates the total of the following series of numbers:
1/30+2/29+3/28+ ... +30/11
Your loop should be especially elegant! Try to write it with only one counter variable. (Hint: First
determine the numerator of each summand, then determine the denominator of each summand, then
form each summand and add it to a running total.)
Answer: r = 0
for i in range(1,31):
r += i / (31 - i)
print(r)
==================================================
Question: Write a class named Month. The class should have
• an int field named monthNumber that holds the number of the month. For example, the
number for January is 1, the number for February is 2, etc.
• a no-arg constructor that sets monthNumber to 1.
• a constructor that accepts the number of the month as an argument and sets the monthNumber
field to the value of this argument. If the value is less than 1 or greater than 12 then the
constructor should set monthNumber to 1.
• a constructor that accepts the name of the month, such as "January" or "February", as a
argument and sets monthNumber to the corresponding integer value.
• a setter for the monthNumber field. If the value passed to the setter is less than 1 or greater
than 12 then the constructor should set monthNumber to 1.
• a getter for monthNumber.
• a getMonthName method that returns the name of the month. For example if the monthNumber
field contains 1, then this method should return the string "January".
Answer: private static final String[] monthNames = { "January", "February",
"March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };

private static final int[] monthDays = { 31, 28, 31, 30, 31, 30, 31, 31,
30, 31, 30, 31 };

private int month;

public Month(int theMonthNumber) {
if (theMonthNumber > 0 && theMonthNumber <= 12) {
month = theMonthNumber - 1;
} else
month = 0;
}

public String toString() {
return getMonthName() + " " + getNumberOfDays();
}
==================================================
Question: Write a class called UpperCaseFile. The class constructor should accept two file names as
arguments. The first file should be opened for reading and the second file should be opened for
writing. The constructor should read the contents of the first file, change all characters to uppercase,
and store the results in the second file. The second file will be a copy of the first file, except that
all the characters will be uppercase. Use Notepad or another text editor to create a simple file that
can be used to test the class.
Answer: import java.util.Scanner; // Need for Scanner.
import java.io.*; // Needed for File and IOException.

public class UpperCaseFile {

// The constructor accepts two file names as its argument.
public UpperCaseFile(String filename1, String filename2) throws IOException {
// Make sure the file exists.
File file1 = new File(filename1);
if (!file1.exists()) {
// Display an error.
System.out.println("The file " + filename1 +
" does not exist.");

// Exit the program.
System.exit(0);
}

// Open the file
Scanner inputFile = new Scanner(file1);

String lines = "";

// Read lines from the file
while (inputFile.hasNext()) {
// Read the info
String readInfo = inputFile.nextLine();

// Convert to uppercase and add it to lines
lines += readInfo.toUpperCase();
}
// Close the input file.
inputFile.close();

// Write data to output file.
PrintWriter outputFile = new PrintWriter(filename2);

// write the info
outputFile.write(lines);

// Close the file.
outputFile.close();

System.out.println("Done!");
}
}



import java.io.*; // Needed for File and IOException.

public class UpperCaseFileDemo {

public static void main(String[] args) throws IOException {
String filename1 = "lowerCase.txt"; // To hold filename1.
String filename2 = "upperCase.txt"; // To hold filename2

// Create the two instances of the UpperCaseFile class.
UpperCaseFile ucf1 = new UpperCaseFile(filename1, filename2);
}
}
==================================================
Question: Write a method called increaseLengths to be included in the Rectangle class on pages 134 and
135 of the text. The increaseLengths method takes an array of Rectangle objects as input and
returns a new array of Rectangle objects. The width of each Rectangle object in the new array is
the same as the width of the corresponding Rectangle object in the original array, but the length of
each Rectangle object in the new array is double the length of the corresponding Rectangle object
in the original array
Answer: .
==================================================
Question: The local Department of Motor Vehicles has asked you to wrote a program that grades the
written portion of the driver's license exam. The exam has 20 multiple choice questions. Here are
the correct answers:
1. B 6. A 11. B 16. C
2. D 7. B 12. C 17. C
3. A 8. A 13. D 18. B
4. A 9. C 14. A 19. D
5. C 10. D 15. D 20. A
A student must correctly answer 15 out of the 20 questions to pass the exam.
Write a class named DriverExam that holds the correct answers to the exam in an array field. The
class should also have an array field that holds the student's answers. The class should have the
following methods:
• passed, which returns true if the student passed the exam and false otherwise.
• totalCorrect, which returns the total number of questions the student answered correctly.
• questionsMissed, which returns an int array containing the question numbers of the questions
the student answered incorrectly.
Demonstrate this class in an application program that asks the user to enter a student's answers,
and then displays the results returned from the DriverExam class' methods. Make sure that your
program validates the user's input by accepting only A, B, C, or D as the student's answers.
Answer: // this should be static since it can be shared between all instances of the test
private static String[] correctAnswers =
{"B", "D", "A", "A", "C", "A",
"B", "A", "C", "D",
"B", "C", "D", "A",
"D", "C", "C", "B", "D", "A"};

// lets leave initializing to the constructor, and
// let's store the values so we only calculate them once
// Also, make sure they are private to restrict access
private boolean[] missed;
private int correct;
private int incorrect;
private String[] userAnswers;

//Process the user's answers
public DriverExam (String[] answers)
{
missed = new boolean[answers.length];
userAnswers = new String[answers.length];
correct = 0;
incorrect = 0;

for (int i = 0; i < answers.length; i++)
{
userAnswers[i] = answers[i];
missed[i] = userAnswers[i].equalsIgnoreCase(correctAnswers[i])
if (!missed[i]) {
correct++;
} else {
incorrect++;
}
}
}

//Returns a boolean value if correct answers > 15
public boolean passed()
{
return correct >= 15; // don't use if/else when you are using a boolean expression
}

/*
* Let's use the values we calculated to make the methods
* very simple and easy to read. In addition, we only calculate things once
* which makes our code more efficient
*/

public int totalCorrect()
{
return correct;
}

public int totalIncorrect()
{
return incorrect;
}

public boolean[] questionsMissed()
{
return missed;
}
==================================================
Question: Write a class named PhoneBookEntry that has fields for a person's name and phone number.
The class should have a constructor and appropriate accessor and mutator methods. Then write
an application program that creates at least five PhoneBookEntry objects and stores them in an
ArrayList. Use a loop to display the contents if each object in the ArrayList.
Answer: public PhoneBookEntry(String name, String phoneNumber) {
super();
this.name = name;
this.phoneNumber = phoneNumber;
}

private String name;
private String phoneNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

@Override
public String toString() {

+ phoneNumber + "]";
}

}


public static void main(String[] args) {

PhoneBookArrayList bookArrayList = new PhoneBookArrayList();

PhoneBookEntry entry1 = bookArrayList.new PhoneBookEntry("Jack", "920-456-2345");
PhoneBookEntry entry2 = bookArrayList.new PhoneBookEntry("Sam", "868-344-2345");
PhoneBookEntry entry3 = bookArrayList.new PhoneBookEntry("George", "414-234-2345");
PhoneBookEntry entry4 = bookArrayList.new PhoneBookEntry("Dimo", "608-049-2345");
PhoneBookEntry entry5 = bookArrayList.new PhoneBookEntry("Jenny", "971-456-2345");

List<PhoneBookEntry> phoneNumberEntries = new ArrayList<>();
phoneNumberEntries.add(entry1);
phoneNumberEntries.add(entry2);
phoneNumberEntries.add(entry3);
phoneNumberEntries.add(entry4);
phoneNumberEntries.add(entry5);

phoneNumberEntries.forEach(number -> System.out.println(number));
}
==================================================