0% found this document useful (0 votes)
21 views17 pages

C# Temperature Conversion Example

The document provides examples and explanations of object-oriented programming concepts like the requirements, design, implementation, and testing stages of program development. It also includes code examples for a Celsius to Fahrenheit temperature conversion program, including an interface for representing temperatures, a class that implements the interface, and a test driver class.

Uploaded by

abundant116
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views17 pages

C# Temperature Conversion Example

The document provides examples and explanations of object-oriented programming concepts like the requirements, design, implementation, and testing stages of program development. It also includes code examples for a Celsius to Fahrenheit temperature conversion program, including an interface for representing temperatures, a class that implements the interface, and a test driver class.

Uploaded by

abundant116
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 1

Object-Oriented Programming

Exercises
1.1 The requirements stage would generate a user manual like that shown here:
User Manual
Enter the string: java CelsiusToFahrenheit <first> <last> <incr>
at the command line, where <first> is the first Celsius temperature to be
converted, <first> is the last Celsius temperature, and <incr> is the Celsius
increment for the table. The output will be a conversion table with that range
and increment.
Example:
Input: java Convert 0 40 10
Output: 032
1050
2068
3086
40104

The design stage could adapt the same class as shown in Listing 1.1.
The implementation stage could adapt the same class as shown in Listing 1.2.
The testing stage could run a test driver like this:
public class CelsiusToFahrenheit {
public static void main(String[] args) {
if ([Link]!=3) exit();
double first = [Link](args[0]);
double last = [Link](args[1]);
double incr = [Link](args[2]);
for (double i=first; i<=last; i += incr)
[Link](i + “\t” + new MyTemperature(value,'F') );
}

1
2 Chapter 1 Binary Trees

private static void exit() {


[Link](
"Usage: java CelsiusToFahrenheit <first> <last> <incr>"
+ "\nwhere:"
+ "\t<first> is the first celsius temperature to be listed"
+ "\t<last> is the last celsius temperature to be listed"
+ "\t<incr> is the increment"
+ "\nExample:"
+ "\tjava CelsiusToFahrenheit 0 40 4" Design
);
[Link](0);
} Implementation
}
1.2 Another likely cycle is shown in here. This is the common Debug
Cycle, consisting of repeated two-part test-and-correct step. Testing
1.3
CombinationLock

-n1:int
-n2:int
-n3:int
-open:boolean

+changeComb(int,int,int,int,int,int):boolean
+close()
+isOpen():boolean
+open(int,int,int):boolean

1.4 If d is a divisor of n that is greater than n , then m = n/d must be a whole number (i.e., an
integer), and therefore another divisor of n. But since d > n , we have m = n/d < n/ n =
n . So by checking for divisors only among those integers that are less than n ,
the existence of the divisor d > n will be found indirectly from m = n/d < n .
1.5
Course

Section

Instructor Student

Person
Solutions 3

1.6
Department Course

Chair Section

Instructor Student

Person

1.7
Course

Section Undergraduate

Instructor Graduate

Person Student

1.8
Vehicle

Bus Car

Driver Owner

Person
4 Chapter 1 Binary Trees

1.9
Bank Manager Person

BankBranch Customer

CheckingAccount Account SavingsAccount

Credit Transaction Debit

1.10
Media

BroadcastMedia PrintMedia Website

RadioProgram TVProgram Periodical Book

Journal Magazine Newspaper

Programming Problems
1.1 /**
* An interface for representing temperatures, with functionality
* for converting their values between Celsius and Fahrenheit.
* @author John R. Hubbard
* @see MyTemperature
*/
Solutions 5

public interface Temperature {


/** @return the Celsius value for this temperature. */
public double getCelsius();
/** @return the Fahrenheit value for this temperature. */
public double getFahrenheit();
/** @return the Kelvin value for this temperature. */
public double getKelvin();
/** @param celsius the Celsius value for this temperature. */
public void setCelsius(double celsius);
/** @param fahrenheit the Fahrenheit value for this temp. */
public void setFahrenheit(double fahrenheit);
/** @param kelvin the Kelvin value for this temperature.*/
public void setKelvin(double kelvin);
}

public class MyTemperature implements Temperature {


private double celsius; // stores temperature as a Celsius value
public MyTemperature(double value, char scale) {
if (scale=='C') setCelsius(value);
if (scale=='F') setFahrenheit(value);
else setKelvin(value);
}
public double getCelsius() {
return celsius;
}
public double getFahrenheit() {
return 9*celsius/5 + 32.0;
}
public double getKelvin() {
return celsius + 273.16;
}
public void setCelsius(double celsius) {
[Link] = celsius;
}
public void setFahrenheit(double fahrenheit) {
[Link] = 5*(fahrenheit - 32)/9;
}
public void setKelvin(double kelvin) {
[Link] = kelvin - 273.16;
}
public String toString() {
// Example: "25.0 C = 77.0 F"
6 Chapter 1 Binary Trees

return round(getCelsius())+ " C = "


+ round(getFahrenheit())+ " F = "
+ round(getKelvin())+ " K";
}
private static double round(double x) {
// returns x, rounded to one digit on the right of the decimal:
return [Link](10*x)/10.0;
}
}
1.2 public class MyTemperature implements Temperature {
private double celsius; // stores temperature as a Celsius value
private int digits; // number of digits to right of decimal
public MyTemperature(double value, char scale, int digits) {
if (scale=='C') setCelsius(value);
else setFahrenheit(value);
[Link] = digits;
}
public double getCelsius() {
return celsius;
}
public double getFahrenheit() {
return 9*celsius/5 + 32.0;
}
public void setCelsius(double celsius) {
[Link] = celsius;
}
public void setDigits(int digits) {
[Link] = digits;
}
public void setFahrenheit(double fahrenheit) {
[Link] = 5*(fahrenheit - 32)/9;
}
public String toString() {
// Example: "25.0 C = 77.0 F"
return round(getCelsius())+" C = "+round(getFahrenheit())+" F";
}
private double round(double x) {
// returns x, rounded to one digit on the right of the decimal:
double p = [Link](10,digits);
return [Link](p*x)/p;
}
}
Solutions 7

public class Convert {


public static void main(String[] args) {
if ([Link]!=3) exit();
double value = [Link](args[0]); // convert string
char scale = [Link](args[1].charAt(0));
int digits = [Link](args[2]);
if (scale!='C' && scale!='F') exit();
Temperature temperature= new MyTemperature(value, scale, digits);
[Link](temperature);
}
private static void exit() {
// prints usage message and then terminates the program:
[Link](
"Usage: java Convert <temperature> <scale> <digits>"
+ "\nwhere:"
+ "\t<temperature> is the temperature that you want to convert"
+ "\n\t<scale> is either \"C\" or \"F\"."
+ "\n\t<digits> is the number of digits to use right of decimal."
+ "\nExample: java Convert 67 F 2"
);
[Link](0);
}
}
1.3 public class MyTemperature implements Temperature {
private static final String s = "###,###,###,###.################";
private double celsius; // stores temperature as a Celsius value
private int digits; // number of digits to right of decimal
private DecimalFormat formatter; // used for formatted output
public MyTemperature(double value, char scale, int digits) {
if (scale=='C') setCelsius(value);
else setFahrenheit(value);
[Link] = digits;
setFormatter();
}
private void setFormatter() {
String pattern = new String([Link](), 0, 16 + digits);
[Link] = new DecimalFormat(pattern);
}
public double getCelsius() {
return celsius;
}
8 Chapter 1 Binary Trees

public double getFahrenheit() {


return 9*celsius/5 + 32.0;
}
public void setCelsius(double celsius) {
[Link] = celsius;
}
public void setDigits(int digits) {
[Link] = digits;
setFormatter();
}
public void setFahrenheit(double fahrenheit) {
[Link] = 5*(fahrenheit - 32)/9;
}
public String toString() {
// Example: "25.0 C = 77.0 F"
return [Link](getCelsius()) + " C = "
+ [Link](getFahrenheit()) + " F";
}
}
public class Convert {
public static void main(String[] args) {
if ([Link]!=3) exit();
double value = [Link](args[0]); // convert string
char scale = [Link](args[1].charAt(0));
int digits = [Link](args[2]);
if (scale!='C' && scale!='F') exit();
Temperature temperature= new MyTemperature(value, scale, digits);
[Link](temperature);
}
private static void exit() {
// prints usage message and then terminates the program:
[Link](
"Usage: java Convert <temperature> <scale> <digits>"
+ "\nwhere:"
+ "\t<temperature> is the temperature that you want to convert"
+ "\n\t<scale> is either \"C\" or \"F\"."
+ "\n\t<digits> is the number of digits to use right of decimal."
+ "\nExample: java Convert 67 F 2"
);
[Link](0);
}
}
Solutions 9

1.4 public class TestPrimeAlgorithm {


public static void main(String[] args) {
Random random = new Random();
for (int i=0; i<100; i++) {
int n = [Link](Integer.MAX_VALUE);
if (isPrime(n)) [Link](n + " ");
}
}
public static boolean isPrime(int n) {
if (n < 2) return false;
if (n < 4) return true;
if (n%2 == 0) return false;
for (int d=3; d*d <= n; d += 2)
if (n%d == 0) return false;
return true;
}
}
1.5 public class Course {
private float credit;
private String dept;
private String id;
private String name;
private Section[] sections = new Section[1000];
public Course(String dept, String id, String name, float credit) {
[Link] = credit;
[Link] = dept;
[Link] = id;
[Link] = name;
}
public void add(Section section) {
int i=0;
while (sections[i] != null)
++i;
sections[i] = section;
}
public String toString() {
String s = dept + " " + id + " \"" + name + "\", "
+ credit + " credits";
for (int i=0; sections[i] != null; i++)
s += sections[i];
return s;
}
10 Chapter 1 Binary Trees

public static void main(String[] args) {


Course course = new Course("CMSC", "221", "Data Structures", 4);
[Link](course);
}
}

public class Section {


private Course course;
private String place;
private String term;
private String time;
private Instructor instructor;
private Student[] students;
public Section(Course course, String term, String p, String t) {
[Link] = course;
[Link] = term;
[Link] = p;
[Link] = t;
}
public Course getCourse() {
return course;
}
public String getPlace() {
return place;
}
public String getTerm() {
return term;
}
public String getTime() {
return time;
}
public Instructor getInstructor() {
return instructor;
}
public Student[] getStudents() {
return students;
}
public void setPlace(String place) {
[Link] = place;
}
public void setTerm(String term) {
[Link] = term;
Solutions 11

}
public void setTime(String time) {
[Link] = time;
}
public void setInstructor(Instructor instructor) {
[Link] = instructor;
}
public void setStudents(Student[] students) {
int n = [Link];
// duplicate the array object:
[Link] = new Student[n];
// but do not duplicate the Student objects:
for (int i=0; i<n; i++)
[Link][i] = students[i];
}
public String toString() {
return course + ": " + term + ", " + place + ", " + time + ", "
+ instructor;
}
public static void main(String[] args) {
Course course = new Course("CMSC", "221", "Data Structures", 4);
Section section = new Section(course, "Fall 2004", null, null);
[Link](section);
}
}

import [Link].*;
public class Person {
protected int yob;
protected String email;
protected String id;
protected boolean male;
protected String name;
public Person(String name, String id, String sex, int yob) {
[Link] = id;
[Link] = ([Link](0,1).toUpperCase() == "M");
[Link] = name;
[Link] = yob;
}
public int getYob() {
return yob;
}
12 Chapter 1 Binary Trees

public String getEmail() {


return email;
}
public String getId() {
return id;
}
public boolean isMale() {
return male;
}
public String getName() {
return name;
}
public void setEmail(String email) {
[Link] = email;
}
public String toString() {
String string = name + ", " + id;
if (male) string += " (M)";
else string += " (F)";
if (email != null) string += ", " + email;
string += " (" + yob + ")";
return string;
}
public static void main(String[] args) {
Person grandson = new Person("C. Hubbard", "1.2.1", "M", 2002);
[Link](grandson);
[Link]("abced@[Link]");
[Link](grandson);
[Link]("\t name: " + [Link]);
[Link]("\t id: " + [Link]);
[Link]("\t sex: "+ ([Link]?"male":"female"));
[Link]("\temail: " + [Link]);
[Link]("\t yob: " + [Link]);
}
}

import [Link].*;
public class Student extends Person {
protected String country;
protected int credits;
protected double gpa;
public Student(String name, String id, String s, int y, String c) {
Solutions 13

super(name, id, s, y);


[Link] = c;
}
public int getCredits() {
return credits;
}
public double getGpa() {
return gpa;
}
public String getCountry() {
return country;
}
public void setCredits(int credits) {
[Link] = credits;
}
public void setGpa(double gpa) {
[Link] = gpa;
}
public void setCountry(List record) {
[Link] = country;
}
public static void main(String[] args) {
Student student =
new Student("Anne Miller", "200491", "F", 1985, "US");
[Link](student);
}
}

import [Link].*;
public class Instructor extends Person {
protected String dept;
protected String office;
protected String tel;
public Instructor(String name, String id, String sex, int yob) {
super(name, id, sex, yob);
}
public String getDept() {
return office;
}
public String getOffice() {
return office;
}
14 Chapter 1 Binary Trees

public String getTel() {


return tel;
}
public void setDept(String dept) {
[Link] = dept;
}
public void setOffice(String office) {
[Link] = office;
}
public void setTel(String tel) {
[Link] = tel;
}
public String toString() {
String s = [Link]();
if (dept != null) s += ", " + dept;
if (office != null) s += ", " + office;
if (tel != null) s += " (" + tel + ")";
return s;
}
public static void main(String[] args) {
Instructor knuth = new Instructor("Don Knuth","8122063","M",1938);
[Link](knuth);
[Link]("CS");
[Link](knuth);
}
}
1.6 public class ComboLock {
private int n1, n2, n3;
private boolean open;
public ComboLock(int n1, int n2, int n3) {
this.n1 = n1;
this.n2 = n2;
this.n3 = n3;
}
public boolean changeComb(int n1, int n2, int n3, int n4,
int n5, int n6) {
if (this.n1 != n1 || this.n2 != n2 || this.n3 != n3) return false;
this.n1 = n4;
this.n2 = n5;
this.n3 = n6;
open = false;
return true;
Solutions 15

}
public void close() {
open = false;
}
public boolean isOpen() {
return open;
}
public boolean open(int n1, int n2, int n3) {
if (this.n1 == n1 && this.n2 == n2 && this.n3 == n3) open = true;
else open = false;
return open;
}
}

public class TestComboLock {


public static void main(String[] args) {
ComboLock lock = new ComboLock(10, 20, 30);
[Link]("[Link](): " + [Link]());
[Link]("[Link](10,20,30): "+[Link](10,20,30));
[Link]("[Link](): " + [Link]());
[Link]();
[Link]("[Link](): " + [Link]());
[Link]("[Link](11,20,30): "+[Link](11,20,30));
[Link]("[Link](): " + [Link]());
[Link]("[Link](11, 20, 30, 11, 22, 33): "
+ [Link](11, 20, 30, 11, 22, 33));
[Link]("[Link](): " + [Link]());
[Link]("[Link](11,22,33): "+[Link](11,22,33));
[Link]("[Link](): " + [Link]());
[Link]("[Link](10, 20, 30, 15, 25, 35): "
+ [Link](10, 20, 30, 15, 25, 35));
[Link]("[Link](): " + [Link]());
[Link]("[Link](15,25,35): "+[Link](15,25,35));
[Link]("[Link](): " + [Link]());
}
}
1.7 import [Link].*;
public class Student extends Person { // Student inherits Person
private String country; // Student aggregates String
private int credits;
private double gpa;
private final Transcript transcript = new Transcript();
16 Chapter 1 Binary Trees

public Student(String name, boolean male, int yob, String c) {


super(name, male, yob);
[Link] = c;
}
public void updateTranscript(Section section, Grade grade) {
[Link](section, grade);
}
public void printTranscript() {
[Link](transcript);
}
private class Transcript { // composition
Map map = new HashMap();
void add(Section section, Grade grade) {
[Link](section, grade);
}
public String toString() {
return [Link]();
}
}
}

package chap01.prob07;
public class TestStudent {
public static void main(String[] args) {
Student joe = new Student("Joe", true, 1983, "IT");
[Link](new Section("CS211.02"), new Grade("A-"));
[Link](new Section("EC110.07"), new Grade("B+"));
[Link]();
}
}
1.8 class Phone {
private String areaCode, number;
public Phone(String areaCode, String number) {
[Link] = areaCode;
[Link] = number;
}
public Phone(Phone that) {
[Link] = [Link];
[Link] = [Link];
}
public void setAreaCode(String areaCode) {
[Link] = areaCode;
Solutions 17

}
public String toString() {
return "(" + areaCode + ")" + [Link](0, 3)
+ "-" + [Link](3);
}
}

public class Person {


private final boolean male;
private final String name;
private final Phone phone;
private final int yob;
public Person(String name, boolean male, int yob, Phone phone) {
[Link] = name;
[Link] = male;
[Link] = yob;
[Link] = new Phone(phone);
}
public String getName() {
return name;
}
public Phone getPhone() {
return phone;
}
public int getYob() {
return yob;
}
public boolean isMale() {
return male;
}
public String toString() {
return (male?"Mr. ":"Ms. ") + name+" ("+yob+"), tel. "+phone;
}
public static void main(String[] args) {
Phone tel = new Phone("808", "4561414");
Person gwb = new Person("G. W. Bush", true, 1946, tel);
[Link](gwb);
[Link]("202");
[Link](gwb);
}
}

Common questions

Powered by AI

Inheritance improves code reusability in the Student and Instructor classes by allowing both to extend the Person class, thereby inheriting properties like name, ID, gender, and year of birth. This avoids redundancy in defining these attributes for each class, enabling reusability and reducing maintenance efforts for shared fields and methods that operate on these attributes .

The setFormatter method in the MyTemperature class is significant because it adjusts the DecimalFormat object to control the number formatting based on the user-defined number of decimal digits. This allows the program to display temperature values with varying precision, enhancing flexibility and usability for different output requirements and rounding needs .

Having the Transcript class as an internal class within the Student class supports encapsulation by restricting the Transcript's scope to its enclosing class. This setup ensures better control and protection of the transcript data, limiting access and modifications to only those operations explicitly permitted by the Student class. This design pattern ensures strong cohesion and better encapsulation of related functionality .

The Convert class utilizes command-line arguments to receive temperature conversion inputs and validate them. It expects three arguments: the temperature value, the scale (either 'C' for Celsius or 'F' for Fahrenheit), and the number of digits for decimal precision. The program checks that the inputs are formatted correctly, with specific input types and values, and terminates the operation with an error message if the inputs are incorrect, ensuring robust input validation .

Encapsulation in the Phone class enhances object safety and integrity by keeping its variables areaCode and number private, exposing only public methods to interact with and modify the phone's state. This limits direct access to the object's internal data, reducing the risk of unauthorized or erroneous updates, while still allowing controlled modifications through explicit setter methods .

In the software development lifecycle for the CelsiusToFahrenheit program, the User Manual serves as an output of the requirements stage, explaining how to use the program. It details the command line input format and expected output, which helps ensure the implementation meets user needs and aids testers in verifying correct behavior as outlined in the planning phases .

The ComboLock class ensures security and functionality through several mechanisms. It stores three combination numbers (n1, n2, n3) and checks if an attempt to open the lock matches these numbers exactly. If they match, the lock sets the 'open' state to true; otherwise, it remains false. The class also provides a method to change the combination only if the current combination is input correctly, adding an additional layer of security .

The Course and Section classes model academic course structures through composition. A Course object contains an array of Section objects, representing different offerings of the course over terms or in different locations. Each Section maintains its relation to a Course object and stores additional details like time, place, and instructor. This relationship allows seamless organization, maintenance, and retrieval of academic offerings and schedules, encapsulating the complexities of course management within the model .

The TestPrimeAlgorithm class uses a moderately efficient algorithm for checking primality. It initially checks small numbers and even divisibility for optimization. For larger numbers, it iterates through potential divisors up to the square root of the tested number, reducing the number of division operations compared to a full check up to the number itself, which improves efficiency. However, checking each odd number and skipping established mathematical shortcuts could still leave room for further optimization .

MyTemperature implements temperature conversion by storing the temperature internally in Celsius and providing methods to convert to Fahrenheit and Kelvin. The getFahrenheit method calculates the Fahrenheit value using the formula 9*celsius/5 + 32, while getKelvin returns celsius + 273.16. Conversely, it also allows setting the temperature in Fahrenheit or Kelvin, converting these to Celsius using the formulas 5*(fahrenheit-32)/9 and kelvin-273.16 respectively .

You might also like