Java How to Program学习笔记_第三章_类、对象、方法及字符串简介(Introduction to Classes, Objects, Methods and Strings)——习题

十年磨一剑,这次复习明显感觉功力有所提升。无论是对基本概念的理解还是解题能力都有提高!

Self-Review Exercises

3.1 Fill in the blanks in each of the following:

a) Each class declaration that begins with keyword Public must be stored in a file that has exactly the same name as the class and ends with the .java filename extension.

b) Keyword class in a class declaration is followed immediately by the class’s name.

c) Keyword new requests memory from the system to store an object, then calls the corresponding class’s constructor to initialize the object.

d) Each parameter must specify both a(n) type and a(n) name .

e) By default, classes that are compiled in the same directory are considered to be in the same package, known as the .

f) Java provides two primitive types for storing floating-point numbers in memory: float and double .

g) Variables of type double represent double-precision floating-point numbers.

h) Scanner method nextDouble returns a double value.

i) Keyword public is an access modifier.

j) Return type void indicates that a method will not return a value.

k) Scanner method nextLine reads characters until it encounters a newline character, then returns those characters as a String.

l) Class String is in package java.lang.

m) A(n) import declaration is not required if you always refer to a class with its fully qualified class name.

n) A(n) floating-point number is a number with a decimal point, such as 7.33, 0.0975 or 1000.12345.

o) Variables of type float represent single-precision floating-point numbers.

p) The format specifier %f is used to output values of type float or double.

q) Types in Java are divided into two categories— primitive types and reference types.

3.2 State whether each of the following is true or false. If false, explain why.

a) By convention, method names begin with an uppercase first letter, and all subsequent words in the name begin with a capital first letter. (F)

b) An import declaration is not required when one class in a package uses another in the same package. (T)

c) Empty parentheses following a method name in a method declaration indicate that the method does not require any parameters to perform its task. (T)

d) A primitive-type variable can be used to invoke a method. (F)

e) Variables declared in the body of a particular method are known as instance variables and can be used in all methods of the class. (F)

f) Every method’s body is delimited by left and right braces ({ and }). (T)

g) Primitive-type local variables are initialized by default. (F)

h) Reference-type instance variables are initialized by default to the value null. (T)

i) Any class that contains public static void main(String[] args) can be used to execute an app. (T)

j) The number of arguments in the method call must match the number of parameters in the method declaration’s parameter list. (T)

k) Floating-point values that appear in source code are known as floating-point literals and are type float by default. (F)

3.3 What is the difference between a local variable and an instance variable?

Answer: A local variable is declared in the body of a method and can be used only from the point at which it’s declared through the end of the method declaration. An instance variable is declared in a class, but not in the body of any of the class’s methods. Also, instance variables are accessible to all methods of the class.

3.4 Explain the purpose of a method parameter. What is the difference between a parameter and an argument?

Answer: A parameter represents additional information that a method requires to perform its task. Each parameter required by a method is specified in the method’s declaration. An argument is the actual value for a method parameter. When a method is called, the argument values are passed to the corresponding parameters of the method so that it can perform its task.

Exercises

3.5 (Keyword new) What’s the purpose of keyword new? Explain what happens when you use it.

3.6 (Default Constructors) What is a default constructor? How are an object’s instance variables initialized if a class has only a default constructor?

3.7 (Instance Variables) Explain the purpose of an instance variable.

3.8 (Using Classes without Importing Them) Most classes need to be imported before they can be used in an app. Why is every app allowed to use classes System and String without first importing them?

3.9 (Using a Class without Importing It) Explain how a program could use class Scanner without importing it.

3.10 (set and get Methods) Explain why a class might provide a set method and a get method for an instance variable.

3.11 (Modified Account Class) Modify class Account to provide a method called withdraw that withdraws money from an Account. Ensure that the withdrawal amount does not exceed the Account’s balance. If it does, the balance should be left unchanged and the method should print

a message indicating "Withdrawal amount exceeded account balance." Modify class AccountTest (Fig. 3.9) to test method withdraw.

3.12 (Invoice Class) Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as instance variables—a part number (type String), a part description (type String), a quantity of the item being purchased (type int) and a price per item (double). Your class should have a constructor that initializes the four instance variables. Provide a set and a get method for each instance variable.

In addition, provide a method named getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a test app named InvoiceTest that demonstrates class Invoice’s capabilities.

3.13 (Employee Class) Create a class called Employee that includes three instance variables—a first name (type String), a last name (type String) and a monthly salary (double). Provide a constructor that initializes the three instance variables. Provide a set and a get method for each instance

variable. If the monthly salary is not positive, do not set its value. Write a test app named EmployeeTest that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary. Then give each Employee a 10% raise and display each Employee’s yearly salary again.

3.14 (Date Class) Create a class called Date that includes three instance variables—a month (type int), a day (type int) and a year (type int). Provide a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and a get method for each instance variable. Provide a method displayDate that displays the month, day and year separated by forward slashes (/). Write a test app named DateTest that demonstrates class Date’s capabilities.

3.15 (Removing Duplicated Code in Method main) In the AccountTest class of Fig. 3.9, method main contains six statements (lines 13–14, 15–16, 28–29, 30–31, 40–41 and 42–43) that each display an Account object’s name and balance. Study these statements and you’ll notice that they differ only in the Account object being manipulated—account1 or account2. In this exercise, you’ll define a new displayAccount method that contains one copy of that output statement. The method’s parameter will be an Account object and the method will output the object’s name and balance. You’ll then replace the six duplicated statements in main with calls to displayAccount, passing as an argument

the specific Account object to output.

Modify class AccountTest class of Fig. 3.9 to declare the following displayAccount method after the closing right brace of main and before the closing right brace of class AccountTest:

public static void displayAccount(Account accountToDisplay)

{

// place the statement that displays

// accountToDisplay's name and balance here

}

Replace the comment in the method’s body with a statement that displays accountToDisplay’s name and balance.

Recall that main is a static method, so it can be called without first creating an object of the class in which main is declared. We also declared method displayAccount as a static method.

When main needs to call another method in the same class without first creating an object of that class, the other method also must be declared static.

Once you’ve completed displayAccount’s declaration, modify main to replace the statements that display each Account’s name and balance with calls to displayAccount—each receiving as its argument the account1 or account2 object, as appropriate. Then, test the updated AccountTest class to ensure that it produces the same output as shown in Fig. 3.9.

Making a Difference

3.16 (Target-Heart-Rate Calculator) While exercising, you can use a heart-rate monitor to see that your heart rate stays within a safe range suggested by your trainers and doctors. According to the American Heart Association (AHA) (www.americanheart.org/presenter.jhtml?identifier=4736), the formula for calculating your maximum heart rate in beats per minute is 220 minus your age in years.

Your target heart rate is a range that’s 50–85% of your maximum heart rate. [Note: These formulas are estimates provided by the AHA. Maximum and target heart rates may vary based on the health, fitness and gender of the individual. Always consult a physician or qualified health-care professional before beginning or modifying an exercise program.] Create a class called HeartRates. The class attributes

should include the person’s first name, last name and date of birth (consisting of separate attributes for the month, day and year of birth). Your class should have a constructor that receives this data as parameters.

For each attribute provide set and get methods. The class also should include a method that calculates and returns the person’s age (in years), a method that calculates and returns the person’s maximum heart rate and a method that calculates and returns the person’s target heart rate. Write a Java app that prompts for the person’s information, instantiates an object of class HeartRates and prints the information from that object—including the person’s first name, last name and date of birth—then calculates and prints the person’s age in (years), maximum heart rate and target-heart-rate range.

3.17 (Computerization of Health Records) A health-care issue that has been in the news lately is the computerization of health records. This possibility is being approached cautiously because of sensitive privacy and security concerns, among others. [We address such concerns in later exercises.]

Computerizing health records could make it easier for patients to share their health profiles and histories among their various health-care professionals. This could improve the quality of health care, help avoid drug conflicts and erroneous drug prescriptions, reduce costs and, in emergencies, could save lives. In this exercise, you’ll design a “starter” HealthProfile class for a person. The class attributes should include the person’s first name, last name, gender, date of birth (consisting of separate attributes for the month, day and year of birth), height (in inches) and weight (in pounds). Your class should have a constructor that receives this data. For each attribute, provide set and get methods.

The class also should include methods that calculate and return the user’s age in years, maximum heart rate and target-heart-rate range (see Exercise 3.16), and body mass index (BMI; see Exercise 2.33). Write a Java app that prompts for the person’s information, instantiates an object of class HealthProfile for that person and prints the information from that object—including the person’s first name, last name, gender, date of birth, height and weight—then calculates and prints the person’s age in years, BMI, maximum heart rate and target-heart-rate range. It should also display the BMI values chart from Exercise 2.33.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值