Review the important terms on Think Java Chapter 2 and Chapter 3.
Converting a decimal number to floating-point format
Programming is to write code that can be executed by the computer to solve a particular problem. A program consists of instructions that a computer can execute. We call instructions written in a high-level programming language statements. In this chapter, we will learn about statements that get input from user, perform computations, store data and computation results in memory and display messages.
The following Java program was first introduced in Chapter 1. In fact, it contains only one statement: System.out.println("My First Java!");
public class MyFirstJava { public static void main(String [] args) { System.out.println("My First Java!"); } }
We can see that the program MUST contain other lines to conform to Java structure rules (i.e. syntax). The following is the class block or "wrap", containing the class header and class block (i.e. the pair of curly brackets).
public class MyFirstJava { }
The following is the method block or "wrap", containing the method header and method block (i.e. the pair of curly brackets).
public static void main(String[] args) { }
We can see that the method block is indented inside the class block. We can also see that the statement is further indented inside the method block. The indentation is for highlighting the structure of a program.
The following is another Java program that contains more statements. We will use it to illustrate some important Java concepts. We can see that the Java file name and the class name have to be the same. Java is case sensitive, which means that upper and lower cases have to match exactly.
public class MySecondJava { public static void main(String [] args) { int studentsPerClass = 28; int totalStudents; double myWeight = 176.3; double myTargetWeight; String greeting = "Hello, "; String name; totalStudents = studentsPerClass * 10; myTargetWeight = myWeight - 8; name = "John"; } }
As introduced in Chapter 1, data are stored in memory. Instead of directly using memory addresses, Java uses variables. When the Java compiler translates a program, a variable is given a specific memory location (address).
In the above program MySecondJava.java, studentsPerClass, myWeight, and greeting are variable names, each representing a memory location for storing data.
We want to choose meaningful names for variables, indicating the purpose of each variable. If the name you choose consists of only one word, spell that word in all lowercase letters, such as greeting. If it consists of more than one word, capitalize the first letter of each subsequent word, such as studentsPerClass and myWeight.
For more information, see this site: Java variable name rules and conventions
A program can process different types of data. We will talk about three basic data types in Java: integer, real value, and text. Integers are whole numbers (without a decimal point). Real values are numbers that include decimal places. Texts are sequences of characters, including punctuation, symbols, and whitespace. Every value in Java has a corresponding data type. The table below shows examples of each of the three types.
Table 1. Basic Data Types
Data Type | Example Values | Java Data Types |
integer | 2, -2, 0, 834529 | byte, short, int, long |
real value | 2.0, -2.235, 0.0, 8329.123782 | float, double |
text | "Hello World!", "Coconut", "0", "4 + 6" | String |
Note that text data are always surrounded by quotes. Some text may look like numbers, but as long as they are surrounded by quotes, they are treated like text.
Java uses its special key words to represent these data types. There are four integer types.
Note: An integer value as in Table 1 is by default as the int type. To represent a long value, we need to append the value with an L or l (i.e. either upper or lowercase). For example, 2L and 23458907234556L are two long values.
The format to represent real values are called floating point. There are two floating-point data types:
An example for converting a decimal number to float
If you are curious, you can watch this video for converting a decimal number to floating-point format. The example used in the video is 13.1875. You will see how it is converted to float.
Note that a real value as in Table 1 is by default the double type. To represent a float value, we need to append the value with an F or f (i.e. either upper or lowercase). For example, 2.0F and -2.235f are two values of the float type.
For text, the data type name is String. Note that, the type name is capitalized.
In Java, each variable must be associated with a certain data type. We use declaration statement to specify the data type of a variable. For example, the following statement declares the variable studentsPerClass as an int variable.
int studentsPerClass;
The following is also a declaration statement. Besides declaring the variable studentsPerClass as an int variable, it also initializes the variable with an int value 28.
int studentsPerClass = 28;
You can also declare multiple variables of the same type in one declaration statement.
int studentsPerClass = 28, totalStudents;
After all the declaration statements in MySecondJava.java are executed, the memory looks like below:
The following statements are assignment statements. Note that they are similar to a declaration statement with an initial value, but there is no data type at the left. These variables have already been declared earlier, so no data types are needed on the left.
totalStudents = studentsPerClass * 10; myTargetWeight = myWeight - 8; name = "John";
An assignment statement puts a new value into a variable. The right side of an assignment statement is first evaluated, and the result will be put into the variable on the left.
The following describes what happens after each of the statements above is executed.
After these assignment statements are executed, the memory looks like below.
Note that if a variable is declared for a certain data type, trying to put a value of another incompatible type will cause a violation of syntax. For example, the compiler will report a syntax error for the following statement, since "168.3" is a String (text) and is not compatible with a double data type.
myTargetWeight = "168.3"; //This will cause a syntax error!
An arithmetic expression (an expression for numeric values) is often used in an assignment statement. For example, studentsPerClass * 10 and myWeight - 8 are both arithmetic expressions. Please refer to Section 2.5 of Think Java for more information on this topic.
Java also has an operator, %, to get remainder of a division. Please refer to Section 3.8 of Think Java for more information on the remainder operator.
Further, Java also has String operations. Please refer to Section 2.8 Think Java for more information on String expressions. This section also talk about how String values and numeric values are "added" together.
For a more detailed introduction to floating-point numbers and the associated rounding errors, please read Section 2.6 and 2.7 of Think Java.
Finally, Java can convert a value of one data type to a value of another data type. For example, (int) 123.56 converts a double value 123.56 to an int value 123. (int) is called a type cast operator. Please refer to Section 3.7 of Think Java for more information on this topic.
The current version of MySecondJava.java does not interact with the user who runs the program at all. Variable declarations and assignments all happen in memory. We will extend the program by adding output statements at the end. They communicate with the user by printing information on the screen.
public class MySecondJava { public static void main(String [] args) { int studentsPerClass = 28; int totalStudents; double myWeight = 176.3; double myTargetWeight; String greeting = "Hello, "; String name; totalStudents = studentsPerClass * 10; myTargetWeight = myWeight - 8; name = "John"; System.out.println(totalStudents); System.out.println(myTargetWeight); System.out.println(greeting + name + "!"); } }
The first output statement will print the value of variable totalStudents, which is 280, on a line. The second output statement will print the value of the variable myTargetWeight, which is 168.3, on the second line. The third output statement will print the result of the String expression greeting + name + "!", which is "Hello, John!" on the third line. Note that the quotation marks are not printed. The following is what the program will print:
280 168.3 Hello, John!
In addition to print and println, you can use System.out.printf to format the output. It’s a very useful method and will be used in many of the exercises at the end of the chapter. Please read Section 3.5 of Think Java on how to have more control on output format.
The following program contains comments. Comments are not instructions for the computer to follow, but instead notes for programmers to read. There are two types of comments in Java. Line comments start with //. Anything following //, on the same line, will not be executed. Often, at the very beginning of a program, comments are used to indicate the author and other information. Even though line comments can be used, but for comments that span several line, we usually use block comments, which start with /* and end with /. Anything in between / and */ will not be executed. Comments are also used to explain tricky sections of code or disable code from executing.
/* MyThirdJava.java Author: ___ ___ The program is for illustrating the order of execution. */ public class MyThirdJava { public static void main(String [] args) { int a = 10; //variable declaration with an initial value int b = 5; //variable declaration with an initial value int sum; //variable declaration sum = a + b; //assignment a = 100; //assignment System.out.println(sum); //output } }
Now take a look at the program, can we give a guess as to what the program will print? Is it 15 or 105?
Some of you will guess 105. The reasoning might be the following: Even though a starts with 10, but it changes to 100. Since variable sum contains the result of a + b, so sum should be 105 at the end. However, this is INCORRECT.
The statements are executed in the order that they show up in the program. When line sum = a + b; is executed, sum gets the value 15. When line a = 100; is executed, a gets a new value 100. Note that sum is not changed and retains the value 15. The output statement thus prints 15.
Read the following program.
/* Miles100ToKMs.java Author: ___ ___ The program is for illustrating the order of execution. */ public class Miles100ToKMs { public static void main(String [] args) { final double KMS_PER_MILE = 1.609; //declare a constant variable double miles = 100.0; double kilometers = miles * KMS_PER_MILE; System.out.println(miles + " miles = " + kilometers + " kilometers"); } }
The first statement final double KMS_PER_MILE = 1.609; declares a constant variable KMS_PER_MILE. Note that the keyword final is prepend to the declaration. For a constant variable, an initial value must be assigned to the variable at the declaration. Also note that, by convention, the name for a constant variable is all capital letters with underscores separating words. However, if a variable’s name is all captial letters, it is not automatically a constant. The keyword final is needed to make a variable constant. Please refer to Section 3.4 of Think Java for more information on constants.
We can see that the program converts 100.0 miles into kilometers. First, variable miles gets a value 100.0. Then the variable kilometers gets a value 160.9. Last the output statement prints the value of the expression miles + " miles = " + kilometers + " kilometers".
Let’s talk about miles + " miles = " + kilometers + " kilometers". It is a mixed-type expression and evaluated to "100 miles = 160.9 kilometers". Please refer to the note below and Section 2.8 Think Java for more information.
String and Numeric Values Mixed Operations
Variables miles and kilometers are double values, while " miles = " and " kilometers" are String values. Since the addition operator + is left-associative, the expression is evaluated from left to right. The following shows how the expression is evaluated:
- First, miles + " miles = " is evaluated. When a numeric value is added to a String value, the Java compiler will insert code to automatically convert the numeric value to the corresponding String value. In this case, miles's value 100.0 is converted to "100.0". Then "100.0" + " miles = " will be performed and results in a longer String "100 miles = ".
- Next, "100 miles = " + kilometers will be evaluated. It is a mixed-type operation and kilometers's value 160.9 is converted to "160.9". "100 miles = " + "160.9" will be carried out and results in "100 miles = 160.9".
- Last, "100 miles = 160.9" + " kilometers" will be evaluated. Both values besides the + operator are String values and they are concatenated, resulting in "100 miles = 160.9 kilometers".
Now we understand the program: It converts 100 miles to the corresponding kilograms. However, this program has a big drawback. What is it?
This program can ONLY convert 100.0 miles. If there is a need to convert 200.0 miles, the programmer will need to modify 100.0 to 200.0. This basically changes the program itself and the program will need to be recompiled. A user will need to get this new program for converting 200.0 miles.
The following is a program that can get user input for distance in miles and then convert it into the corresponding kilometers. There is no need to modify and recompile the program for converting different values. The program can be run as many times as needed to convert whatever the values to be converted.
/* MilesToKMs.java Author: ___ ___ The program is for illustrating the order of execution. */ public class MilesToKMs { public static void main(String [] args) { final double KMS_PER_MILE = 1.609; //declare a constant variable java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter the distance in miles: "); double miles = input.nextDouble(); double kilometers = miles * KMS_PER_MILE; System.out.println(miles + " miles = " + kilometers + " kilometers"); } }
The following are three new lines in the above program:
java.util.Scanner input = new java.util.Scanner(System.in); //new line 1 System.out.print("Enter the distance in miles: "); //new line 2 double miles = input.nextInt(); //new line 3
The second line is an output statement that prints a prompt for a user. It tells the user that the program expects a distance in miles to be entered. We will focus on the other two lines. We will talk about the first and third line below.
Line 1 java.util.Scanner input = new java.util.Scanner(System.in); looks complicated, but a closer look tells us that it’s a declaration statement with an initial value assigned to the declared variable. The data type is java.util.Scanner, the variable is input, and the initial value is new java.util.Scanner(System.in);.
The data type java.util.Scanner looks very long, but it really is Scanner. We will rewrite the program above as follows:
/* MilesToKMs.java Author: ___ ___ The program is for illustrating the order of execution. */ public class MilesToKMs { public static void main(String [] args) { final double KMS_PER_MILE = 1.609; //declare a constant variable Scanner input = new Scanner(System.in); System.out.print("Enter the distance in miles: "); double miles = input.nextDouble(); double kilometers = miles * KMS_PER_MILE; System.out.println(miles + " miles = " + kilometers + " kilometers"); } }
We used the import statement import java.util.Scanner; to tell the Java compiler that data type Scanner is defined in the package java.util of the Java installation. A package contains multiple related classes. java.util.Scanner; is the full pathname of the data type Scanner. If we use the import statement, there is no need to use the full name in the remainder of the program. As a result,
java.util.Scanner input = new java.util.Scanner(System.in);
is simplified to
Scanner input = new Scanner(System.in);
Word new is a keyword for creating a new object. The expression new Scanner(System.in) creates a Scanner object that will extract information from System.in (see the note below). This object is assigned to the variable input. Note that when an object is assigned to a variable, the reference (or location) of the object is stored in the variable.
Scanner, System, System.out, and System.in
Scanner is a data type defined in class Scanner (in file Scanner.java). Similarly, the data type String is also a class defined String.java__ file. The reason that we don’t need an import statement for String is because String belongs to the java.lang package, which is imported automatically.
System is another class in the java.lang package. It is a class that provides methods related to the "system" or environment where programs run.
System.out is an object contained in the System class. It represents the standard output device, normally the monitor.
System.in is an object representing the standard input device, normally the keyboard.
Remember that we can invoke the print and println methods on System.out by System.out.print(…) or System.out.println(…) to print information.
Similarly, we can also invoke different methods on a Scanner object to retrieve different types of information. For example, input.nextInt() will invoke the nextInt method on the Scanner object input and retrieves an integer. See Table 2 for more Scanner methods.
Table 2: Scanner Methods
Method | Description |
---|---|
nextInt() | retrieve an int value |
nextDouble() | retrieve a double value |
next() | retrieve a word (a word is a sequence of characters with no space or tab or newline) |
nextLine() | retrieve a line of characters |
When the statement double miles = input.nextDouble(); is executed, the program will wait and allow the user to enter data. Whatever the user enters will be retrieved and returned by the nextDouble method and then assigned to the variable miles.
See the step-by-step walkthrough of this program at Java Visualizer.
Note that when using nextLine and the other next methods (e.g. next, nextDouble, nextInt) together, there is an unexpected behavior. Please read Section 3.9 of Think Java to understand this phenomenon and how to deal with this issue in your program.
Java designers want to make life easier for Java developers and they designed some short-cut assignment operators to save typing time.
Let’s look at the following three statements. You might say, "Hi, x cannot be equal to x + 5!"
x = x + 5;
We need to remember, however, that this is not a math equation, but an assignment statement. The right side of an assignment statement, which is always an expression, is first evaluated. The value of the expression will be assigned to the variable on the left.
Assume x's original value is 10, x + 5 is evaluated to 15 and then 15 will be put into x. After the assignment statement is executed, x's value becomes 15.
For assignment statements that have similar format, Java has a set of augmented assignment operators. For example, the statement on the left of each line below is equivalent to the statement on the right. The operators used in the statements on the right side are the augmented assignment operators +=, −=, *=, /=, %=. Note that there is no space inside the operators.
x = x + 5; <==> x += 5; x = x − 5; <==> x −= 5; x = x * 5; <==> x *= 5; x = x / 5; <==> x /= 5; x = x % 5; <==> x %= 5;
Note that the format of the original assignment statement has to be the following, where both <var>'s refer to the same variable.
<var> = <var> <operator> <expression>
It’s tricky when <expression> is more complicated than a single item. For example,
x = x − 5 + 4;
is not equivalent to
x −= 5 + 4; //WRONG
Instead, we need to convert the original assignment statement to the following before converting it using the augment assignment operator +=.
x = x − (5 − 4);
and then it can be safely converted to the following equivalent statement:
x −= 5 − 4; //CORRECT
If a variable is increased by 1 or reduced by 1, there are ways to further save typing. We can use increment operator ++ and decrement operator −−. On each line, all statements are equivalent.
x = x + 1; <==> x += 1; <==> x++; <==> ++x; x = x − 1; <==> x −= 1; <==> x−−; <==> −−x;
There are some differences between the following pairs, if you used increment or decrement operators inside another statement.
x++ (post-incrementation) v.s. ++x (pre-incrementation) x−− (post-decrementation) v.s. −−x (pre-decrementation)
For x++, the value of x is used before x is incremented. For example, for the following two statements, x’s value 10 first assigned to y and then x is incremented to 11, so after both statements are executed, x is 11 and y is 10. .
x = 10;
y = x++;
For ++x, x is incremented first before the value of x is used. For example, after for the following two statements, x is first incremented to 11 and then its value 11 is assigned to y, so after both statements are executed, x is 11 and y is 11.
x = 10;
y = ++x;
We will not dive too deep into this topic here. We believe that it makes code difficult to read and, therefore, we discourage this practice.
Write a program to convert 100 Fahrenheit to the corresponding temperature in Celsius. User proper variable names for the temperature in Fahrenheit and thee temperature in Celsius. Include a proper arithmetic expression to do the conversion.
Write a program that does the following:
American format: Thursday, July 16, 2015
European format: Thursday 16 July 2015
The final output should be in the following format. Note that the actual date should be for 2019 Labor Day.
The point of this exercise is to (1) use some of the arithmetic operators, and (2) start thinking about compound entities (like time of day) that are represented with multiple values.
Hint: You might want to use additional variables to hold values during the computation. Variables that are used in a computation but never displayed are sometimes called “intermediate” or “temporary” variables.
Write a program that converts a temperature from Celsius to Fahrenheit. It should
Here is the formula. Be careful not to use integer division! F = 9/5 C + 32
Write a program that calculates the base area and volume of a cylinder, given the radius of the base circle and the length of the cylinder. Please use 3.1416 as the PI value.
Write a program that convert a given total number of seconds into hours, minutes and seconds. It should (1) prompt the user for input, (2) read an integer from the keyboard, (3) calculate the result, and (4) display the output.
The following are two examples:
Given the length, width and height of the room, number of windows and number doors, the program will calculate the gallons and quarts of paint are needed to paint the room. For gallons, print an integer value. For the quarts, print a real number, no need to round down to integer.
Assume that (1) ceiling is painted, (2) 1 gallon of paint covers about 350 square feet, (3) each window is 15 square feet, and (4) each door is 21 square feet.
Write a program that prompts the user to enter a number between 0 and 1000 (not including 1000) and print the digits in reverse order. The following are some examples:
Write a program that prompts the user to enter a monthly saving amount and displays the account value after each of the first six months. When displaying the account values, please use printf to print only two decimal places.
We will assume that the yearly interest is 5%. Please declare a constant variable for the monthly interest rate as follows in your program:
final double MONTHLY_RATE = 0.05/12;
The following are how to calculate the account value at the end of each month:
month1Value: monthlySaving * (1+MONTHLY_RATE)
month2Value: (monthly1Value + monthlySaving) * (1+MONTHLY_RATE)
month3Value: (monthly2Value + monthlySaving) * (1+MONTHLY_RATE)
and so on
Write a program to calculate how many mile, feet, and inches a person walks a day, given the stride length in inches (the stride length is measured from heel to heel and determines how far you walk with each step), the number of steps per minute, and the minutes that person walks a day. Note that 1 mile is 5280 feet and 1 foot is 12 inches. In your program, there should be the following constants:
final int FEET_PER_MILE = 5280; final int INCHES_PER_FEET = 12; final int INCHES_PER_MILE = FEET_PER_MILE * INCHES_PER_FEET;
Hints: In the computation step, your program should first calculate the total inches that person walks a day. Then convert it to miles, remaining feet, and remaining inches. All variables should be of int type.
Write a program that prompts user to enter the weight in pounds (real value) and height in feet and inches (both integers) and then calculates the BMI of the person. Please limit the print out of the BMI value to two decimal digits using printf.
Note that
1 kilogram is 2.2 pounds.
1 inch is 0.0254 meters.
Your program first need to convert pounds to kilograms (i.e. pounds/2.2) and inches to meters (i.e. inches * 0.0254) and then use the following formula to calculate BMI:
kilogram / (meter)^2
Write a program to calculate the cost of a trip. The program prompts user to enter the distance in miles of the trip, the car efficiency in miles per gallon, and the cost of gas in dollars per gallon. Please limit the print out of the cost to two decimal digits using printf.