Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.
To gain experience with
Numbers are essential to computing. In Java there are two fundamental numeric types: integers and floating point numbers. Integers have no decimal 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 it. When a variable is declared, it contains whatever value is leftover 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 new variable to zero in order to avoid having it contain a random value.
Are the following ints and doubles properly declared and/or initialized? If not, supply a correction.
When declaring a variable, take a moment to consider by what name it will be known. A valid name is made up of characters from the set:
Actually, Java permits you to use other alphabetical characters such as Ä or ç in variable names as well, but it can then be difficult to move your source code to other systems. It is best to stick to Roman letters without accents.
The only limitation is that a variable name can't begin with a digit. Of course, 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 like 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:
Mostly, this will happen if the name selected is descriptive enough to tell a human reader how a variable is being used, for example countMessages, userPreference, customerName
Complete the following table of (bad) variable names, better names and descriptions.
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 transform 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 constant descriptions listed below
Even carefully named variables are rarely sufficient to fully convey the operation of a program. They do not, for example, provide an explanation of a future feature that could be implemented because of how something is done now, or leave a detailed description of how a variable is computed. You can however place any additional information necessary in a comment. Comments are plain text for humans to read. They are separated from the machine readable code needed by the compiler by either of:
/* say whatever you want in here, between the slash-asterisk boundaries the compiler will ignore it . . . */
or
// say what ever you want from the double slashes to the end of the line . . . // the compiler will ignore it // . . .
From both design and documentation perspectives, it is a good idea to get in the habit of commenting your code as early as possible. For example, provide a brief description of what the program Coins3.java from the textbook does.
/* your work goes here--use // or /* as appropriate */ public class Coins3 { public static void main(String[] args) { final int PENNY_VALUE = 1; final int NICKEL_VALUE = 5; final int DIME_VALUE = 10; final int QUARTER_VALUE = 25; final int DOLLAR_VALUE = 100; int pennies = 8; // the purse contains 8 pennies, int nickels = 0; // no nickels int dimes = 4; // four dimes int quarters = 3; // and three quarters // compute total value in pennies int total = pennies * PENNY_VALUE + nickels * NICKEL_VALUE + dimes * DIME_VALUE + quarters * QUARTER_VALUE; // use integer division to convert to dollars, cents int dollar = total / DOLLAR_VALUE; int cents = total % DOLLAR_VALUE; System.out.print("Total value = "); System.out.print(dollar); System.out.print(" dollar and "); System.out.print(cents); System.out.println(" cents"); } }
Now, extend Coins3.java to count a number of half dollars and Susan B. Anthony $1 coins, placing the finished code here. Add a comment to show when you modified the code, and what change you made.
In this book, you use a special ConsoleReader class to read input from the keyboard. (The Java library has only limited and cumbersome support for reading numbers from the keyboard.) In Coins4.java, for example, you used pennies = console.readInt(); to get user input..
The ConsoleReader class is contained in a separate file, ConsoleReader.java. Explain what you need to do on your computer system to compile the Coins4.java file together with the ConsoleReader.java file.
The ConsoleReader reads a line of input at a time, and then converts that line to an integer (in the readInt) method or a double (in the readDouble method). The line must contain a single number and nothing else, not even extra spaces. If the user provides input of the wrong kind, then the program terminates. (You will learn later in this course how to implement better error handling. For now, just be careful when you type in input.)
For example, if the user has typed
l0
(with a letter l) instead of
10
then the program terminates.
Try this out with the Coins4 program. Supply bad input. What message does the program display? Type or paste the message into the text field below.
Do the following lines of input data work properly? Why or why not?
User Input: 24 25 Program code: int n1 = console.readInt(); int n2 = console.readInt();
User Input: (look carefully) 4 25 Program code: int n1 = console.readInt(); int n2 = console.readInt();
Values on both sides of an assignment (=) operator are checked to insure that the data received matches the data type of the variable to which it will be assigned. Are the right and left hand sides of the assigment operators of compatible type in the following statements?
What error does your compiler give in these cases?
Because a variable of any given type represents a fixed amount of space in memory, there is a limit to how large a value it can store.
Size limitations are particularly evident with integers. In Java, integers can go up to a little more than 2,000,000. What is the largest value your compiler will accept for an integer? What is the most negative allowed value?
Computations with floating point numbers have finite precision. Can you explain the values your compiler assigns to f and g in:
double f = Math.pow(10.0, 20.0) - 53.4; double g = f + 53.4; System.out.println(f); System.out.println(g);
Recalling what you've learned about integers and floating point values, what value is assigned to x by each of the following?
Translate the following algebraic expressions into Java :
x y = --- 1-x
Many programs manipulate not just numbers but text. Java stores text in string variables. They are declared and assigned in a manner similar to a numeric variable, and the sequence may have any length. (A string may even have length 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.
string temp = name;
assigns the content of variable name to variable temp
System.out.println(name);
displays the contents of variable name on the standard output stream.
Given:
String firstName = "John"; String lastName = "Smith"; String name;
What value will name contain after
name = firstName + lastName;
How could the preceding be revised to give a better result?
The primary difference between strings and numeric data types is that any portion of the characters in a string variable is itself a string variable. Such a portion is called a substring.
What will be the resulting substring in the following examples? If invalid, give a corrected version of the call to substring.
Using substring and concatenation, give a program containing a sequence of commands that will extract characters from inputString = "The quick brown fox jumped over the lazy sleeping dog" to make outputString = "Tempus fugit". Then print outputString.
The number3 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".
Write a program to convert the contents of the variables int year, double increase and string what into a String sentence of the form "In ..., there was a net increase of ...% in ...". Then print the contents of that String variable.
For example, if the user of this sample program provides the following input:
year: 1996 increase: 14.7 what: net sales
then set sentence to:
"In 1996, there was a 14.7% increase in net sales."
The functions Integer.parseInt and Double.parseDouble convert a string containing digits into its numerical value. For example, Integer.parseInt("3") is the number 3.
The readLine method of the ConsoleReader class reads a single input line. Write a program that uses readLine along with the string function substring and Double.parseDouble to parse two lines of user input containing a statement of the form DEPOSIT amount followed by WITHDRAW amount. For example, the input
DEPOSIT 525.40 WITHDRAW 150
will result in account being assigned the value 355.40 . (Since you don't yet know how to implement decisions, you can rely on the fact that the first line is always a deposit and the second line is always a withdrawal.) Then print the output: Balance is 355.40.
Don't forget to send your answers when you're finished.