Download Samples from Chapter 2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Simple Programs from Chapter 2
Putting the Building Blocks All
Together
(corresponds with Chapter 2)
Programming Style and
Documentation

Comments


Indentation and Spacing


Proper indenting makes the code reflect the actual logic of the
program.
Block Styles


Comments are very important. You should comment your code
in order to provide explanations of what the program is doing
Placement of the { and } braces
Naming conventions


Use descriptive names for classes, methods, and variables
By convention, class names begin with uppercase, method and
variable names begin with lowercase, and constants are all
uppercase.
Comments




// for single line
/* */ for multiple lines
Comment at top of source file to identify
the author and the purpose of the
program
Comment to describe classes, methods,
and sections of code (steps of the
algorithm)
Comments help readers understand the program code!
Indentation and Spacing



Statements within blocks should be
indented
Statements that are executed within
control structures should be indented
If a statement continues from one line to
the next, the subsequent line(s) should be
indented.
Block Styles

Choices:

Next-line:
void myMethod()
{
---------
}

End-of-line:
void myMethod(){
---------
}
Either way is fine
Naming Conventions

Variables and method names:

Use lowercase. If the name consists of
several words, concatenate all in one, use
lowercase for the first word, and capitalize
the first letter of each subsequent word in
the name. For example, the variables
radius and area, and the method
computeArea.
Naming Conventions, cont.

Class names:


Capitalize the first letter of each
word in the name. For example,
the class name
TestComputeArea.
Constants:

Capitalize all letters in constants.
For example, the constant PI.
Chapter 2 Examples






ComputeArea (Listing 2.1, p27)
TestScanner (Listing 2.6, p45)
ComputeLoan (Listing 2.7, p46)
ComputeChange (Listing 2.8, p48)
ShowCurrentTime (Listing 2.9, p50)
ComputeLoanUsingInputDialog (Listing 2.10,
p57)
Putting it all together: Listing 2.1
(available from Liang Code Samples)
Putting it all together: Listing 2.1
Variable declarations
Assignment of
literal value into
variable
Arithmetic expression and
assignment
Output with concatenated data values.
A method Call
The System
class…this The name
contains
(identifier)
static
of the
member
member
variable
variable
(out).
The member
variable (out)
is an instance
of another
class (called
PrintStream)
PrintStream has a
non-static
(instancespecific) method
called println
System.out.println("The area for the circle of radius "
+ radius + " is " + area);
The arguments passed to the
println method
This method does not return a value
no assignment
About the System Class
Part of the Java Class Library
 Useful for standard input (keyboard)
and output (screen) in console-based
applications
 More details from Sun’s Java
documentation site:


http://java.sun.com/javase/6/docs/api/
Java documentation from
Sun’s Java site
Putting it all together: Listing 2.1
A package is a collection of
classes. In practice, a package
is equivalent to a directory
(folder). To indicate that a
class is in a package, you
must:
1) Place the .java file in the
appropriate folder, and
2) Write a package statement
with the appropriate package
name as the first line of code
in the .java file.
The ch02 package consists of all
the classes (ComputeArea,
ComputeChange,
ComputeMortgage,
InputDialogDemo,
MyInput,
ShowCurrentTime,
ShowRuntimeErrors,
ShowSyntaxErrors,
TestMyInput).
Listing 2.10 ComputeLoanUsingInputDialog
Listing 2.10 ComputeLoanUsingInputDialog
If you are using a class
that is not in your own
package, or in the package
java.lang, you must import
that class.
Listing 2.10 ComputeLoanUsingInputDialog
Input from user and convert to
appropriate data type.
User Input via JOptionPane Object

JOptionPane is a class in the Java class
library that can display an input dialog for
obtaining user input or show message
dialogs for display to the user.

Two methods:
showInputDialog – for user input
 showMessageDialog – for displaying a message to
the user

The JOptionPane
class…this
contains static
methods for
displaying
various types of
dialogs
The JOptionPane
class’s
ShowInputDialog
method displays a
dialog with
parameters
controlling the
look.
String annualInterestRateString = JOptionPane.showInputDialog(
"Enter yearly interest rate, for example 8.25:");
After the user enters a
value and clicks OK, the
value is returned as a
String. Here, we assign
that value into a String
variable
String annualInterestRateString = JOptionPane.showInputDialog(
"Enter yearly interest rate, for example 8.25:");
In this case, the variable nnualInterestRateString
will contain the string “5.8”.
Listing 2.10 ComputeLoanUsingInputDialog
Simple arithmetic
expressions and
assignments. NOTE:
variables are declared and
initialized in one statement.
Listing 2.10 ComputeLoanUsingInputDialog
Note the use of the cast
operator. This use is a clever
way to make sure that the
displayed output has no
more than two decimal
places.
Anatomy of an arithmetic statement involving
casting
(assume that monthlyPayment had been calculated as 1525.875)
152587.5
(1)
152587 (2)
Casting from double to int truncates
Assign into
variable
monthlyPayment
(4)
1525.87 (3)
Listing 2.10 ComputeLoanUsingInputDialog
A more complex arithmetic
expression and
assignment. Here the
expression includes:
1. Parentheses to
override normal
operator precedence.
2. Calling another method
and passing arguments
Anatomy of a Complex Arithmetic Expression
8) Assign results to monthlyPayment
1) Declare the variable
7) Do the multiplication and division
2) Perform
calculation
3) Perform
calculation
4) Call the Math.pow method passing the
results of (2) and (3) as arguments.
5) Divide the result of (4) into the number 1
6) Subtract the result of (5) from the number 1
About the Math Class



Part of the Java Class Library
Contains methods for performing basic
numeric operations such as
exponentiation, logarithm, square root,
and trigonometric functions.
More details from Sun’s Java
documentation site:

http://java.sun.com/j2se/1.5.0/docs/api
Java documentation from
Sun’s Java site
The Scanner Class
Another way to do User Input
1. Create a Scanner object
Scanner scanner = new Scanner(System.in);
2. Use the methods next(), nextByte(), nextShort(),
nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean() to obtain to a string, byte, short, int, long,
float, double, or boolean value. For example,
System.out.print("Enter a double value: ");
Scanner scanner = new Scanner(System.in);
double d = scanner.nextDouble();
Listing 2.6 TestScanner
Listing 2.6 TestScanner
If you are using a class
that is not in your own
package, or in the package
java.lang, you must import
that class.
Listing 2.6 TestScanner
Creating an instance of the
Scanner class, associating it with
the standard input stream
(System.in), and assigning a
reference to that instance into the
variable called input.
Listing 2.6 TestScanner
Input from user via
scanner, by calling
the input method
that reads user
input for the
appropriate data
type.
How Scanner-based User I/O looks in NetBeans
System.out.print and
System.out.println sends
standard output to Output
window, and the Scanner reads
from the same window
Summary:
User Input/Output Options

Standard I/O Streams



GUI (popup dialogs)



Input: Scanner class and methods
Output: System.out.print (or println)
Input: JOptionPane.ShowInputDialog
Output: JOptionPane.ShowMessageDialog
Many more GUI options…we’ll study later
in semester