<<

APCS CH 4 WS ANSWERS Name:

1. are essential to computing. In Java there are two fundamental numeric types: and floating-point numbers. Integers have no fractional part, whereas floating-point numbers do. Variables of either type are represented by user-specified names. Space in the computer's memory is associated with the name so that the variable acts like a container for the numeric data.

Declaring a variable reserves space in memory and associates a specified name with that space. When a variable is declared, it contains whatever value is left over from the previous use of the memory space. Initializing a variable sets it to a specific value. If no specific value is known, it's a good idea to initialize a new variable to zero in order to avoid having it contain a random value. type name = value; int identifier; /* Variable declared but not initialized */ int identifier = 0; /* Variable declared and initialized to zero */ double identifier = value; /* Variable declared and initialized to another value*/

Correct the errors in the following variable declarations:

1) double 3.14159; double =3.14159;

2) int; int amount;

3) double = 314.00; double amount = 314.00;

4) int double_value = 314.00; double value = 314.00;

5) int_value 314; int value = 314;

6) double working_value 314; double workingValue =314;

2. When declaring a variable, you must also give it a name. A valid name is made up of characters from the :

ABCDEFGHIJKLMNOPQRSTUVWXYZ upper case letters abcdefghijklmnopqrstuvwxyz lower case letters 0123456789 digits _ the underscore character

Actually, Java permits you to use other alphabetical characters, such as Ä and ç in variable names as well, but these characters may cause difficulty if you want to move your source code to other systems. It is best to stick to Roman letters without accents.

A variable name cannot begin with a digit, and the name must be unique. Neither you nor the compiler would be able to distinguish between variables with the same name. For some simple cases, using single letters such as i, j, k is enough, but as programs grow larger this becomes less informative. Like the name for a product or service, a variable name should do two things:

- be unique - express the purpose

A good variable name is descriptive enough to indicate to a human reader how a variable is being used, for example countMessages, userPreference, or customerName.

Complete the following table by renaming the bad variable names and providing descriptions.

Bad Variable Name Variable Renamed Description

double current profit; 1) currentProfit 2) dollars of profit

counts products sold 3) int monthlyCount; 4) int productCount; this month

double %increase; 5)double percentInc; 6) percentincrease

dollars earned this 7)double dollars; 8)double monthEarnings; month

3. Like variables, any numeric constants used by your program should also have informative names, for example:

final int FLASH_POINT_PAPER = 451 or final int BOILING_POINT_WATER = 212. Using named constants transforms statements such as

int y = 451 - x + 212

into the more intelligible

int y = FLASH_POINT_PAPER - x + BOILING_POINT_WATER.

Give definitions for each of the descriptions listed below.

Constant Definition Description 1)final int DAYS_PER_WEEK=7; of days in a week

2) final int WEEKS_PER_YEAR=52; Number of weeks in a year

3) final double WAGE_MIN=11.50; Minimum wage per hour

4. Values on both sides of an assignment (=) operator should be checked to verify that the data received matches the of the variable to which it will be assigned. Fix the right-hand sides of the following assignments so that they are the correct type for the variable on the left side.

int x = Math.sqrt(4); 1) int x = (int) Math.sqrt(4); double y = "3"; 2) double y=3.0; String z = 3.14; 3) String z= “3.14”;

5. What is wrong with each of these assignments?

Statement Error a + 2 = 3; 1)can’t assign value to an Math.PI = 3; 2)Can’t change a constant value x == x + 1; 3)Can’t use == for assignement

6. Computations with floating-point numbers have finite precision. What values are assigned in the following assignments? in:

Statement Value double x = Math.pow(10, 20) + 1; 1) 1 X 10 20 double y = x - 1; 2) 1 X 10 20 double z = x - y;; 2) 0.0

Why? The precision of double only allows for 15 significant decimal digits so the 1 in x is lost.

7. Recalling what you've learned about integers and floating-point values, what value is assigned to x by each of the following?

int x = 6 / 3; 1) 2

int x = 7 / 3; 2) 2

double x = 7 / 3; 3) 2

int x = 7 % 3; 4) 1

int x = 6 % 3; 5) 0

int x = 999 / 1000; 6) 0

double x = 999.0 / 1000.0; 7) .999

int x = (int)(999 / 1000.00); 8) 0

8. Translate the following algebraic expressions into Java:

a. y = x + 1/2 y = x + 1 / 2.0;

b. y = x2 + 2x + 1

y = Math.pow( x, 2)+ 2 * x + 1; X . y = --- y = x / (1-x); 1-x

9. Many programs manipulate not just numbers but also text. Java stores text in string variables. They are declared and assigned in a manner similar to a numeric variable. The may have any length. A string may even have a length of zero. Such a string is called an empty string, and it is denoted as "". For example,

String name = "Joan Wilson";

assigns the 11 characters enclosed in quotes to the variable name.

Given:

String firstName = "Joan"; String lastName = "Wilson"; String name;

1) What value will name contain after

name = firstName + lastName;

"JoanWilson"

2) How could the preceding be revised to give a more readable result?

name = firstName + " " + lastName;

10. What will be the resulting substring in the following examples?

string name = "John Smith" string firstName = name.substring(0, 4); 1)_"John"__ string name = "John Smith" string lastName = name.substring(5, 6); 2)____"S"______string name = "Jane Smith" string name2 = name.substring(1, 11); 3)_"ane Smith"______

11. Using substring and concatenation, give a program containing a sequence of commands that will extract characters from inputString = "The quick brown fox jumps over the lazy dog" to make outputString = "Tempus fugit". Then print outputString. public class SubStringFun

{ public static void main (String [] args)

{ String inputString = "The quick..."; String outputString = inputString.substring(0,1)+ inputString.substring(2,3)+ inputString.substring(22,24)+ inputString.substring(21,22)+ inputString.substring(24,26)+ inputString.substring(16,17)+ inputString.substring(5,6)+ inputString.substring(42)+ inputString.substring(6,7)+ inputString.substring(31,32);

System.out.println(outputString); } } 12. The number 3 and the string "3" are completely different values. But for various purposes, numeric types sometimes need to be used as strings, and for calculation purposes, strings that contain numbers need to be used as numbers.

In Java, it is very easy to convert a number to a string. Simply concatenate with the empty string "". For example, if x has the value 3, then "" + x is the string "3".

Consider the class

class SalesActivity { . . . private int year; private double percentIncrease; private String article; }

Write a method String getDescription to return a sentence of the form "In ..., there was a net increase of ...% in sales of ...".

For example, if the settings of the fields are:

year: 1996 increase: 14.7 what: widgets

then return the string

"In 1996, there was a 14.7% increase in sales of widgets."

public String getDescription() { String sentence = "In " + year + " there was a net increase of "+ percentIncrease + "% in sales of " + article;

return sentence; }

13. Using JOptionPane.showInputDialog, ask the user to supply two integers a and b. Then print out the values a / b and a % b.

Note that you need to use the .parseInt method to convert the input strings to integer values.

String input = JOptionPane.showInputDialog ("Please supply an integer"); int a = Integer.parseInt(input); String input = JOptionPane.showInputDialog ("Please supply another integer"); int b = Integer.parseInt(input); System.out.println("Quotient: " + (double)a/b); System.out.println("Modulus: " + a % b);