simple programs from chapter 2 putting the building blocks all together (corresponds with chapter 2)
TRANSCRIPT
Simple Programs from Simple Programs from Chapter 2Chapter 2
Putting the Building Blocks All Putting the Building Blocks All TogetherTogether
(corresponds with Chapter 2)(corresponds with Chapter 2)
Programming Style and Programming Style and DocumentationDocumentation
CommentsComments Comments are very important. You should comment your Comments are very important. You should comment your
code in order to provide explanations of what the program code in order to provide explanations of what the program is doingis doing
Indentation and SpacingIndentation and Spacing Proper indenting makes the code reflect the actual logic of Proper indenting makes the code reflect the actual logic of
the program. the program. Block StylesBlock Styles
Placement of the { and } braces Placement of the { and } braces Naming conventionsNaming conventions
Use descriptive names for classes, methods, and variablesUse descriptive names for classes, methods, and variables By convention, class names begin with uppercase, method By convention, class names begin with uppercase, method
and variable names begin with lowercase, and constants and variable names begin with lowercase, and constants are all uppercase.are all uppercase.
CommentsComments // for single line// for single line /* */ for multiple lines/* */ for multiple lines Comment at top of source file to Comment at top of source file to
identify the author and the purpose identify the author and the purpose of the programof the program
Comment to describe classes, Comment to describe classes, methods, and sections of code (steps methods, and sections of code (steps of the algorithm)of the algorithm)
Comments help readers understand the program code!
Indentation and SpacingIndentation and Spacing
Statements within blocks should be Statements within blocks should be indentedindented
Statements that are executed within Statements that are executed within control structures should be indentedcontrol structures should be indented
If a statement continues from one If a statement continues from one line to the next, the subsequent line to the next, the subsequent line(s) should be indented.line(s) should be indented.
Block StylesBlock Styles
Choices:Choices: Next-line:Next-line:
void myMethod()void myMethod()
{{------------------
}} End-of-line:End-of-line:
void myMethod(){void myMethod(){------------------
}}
Either way is fine
Naming ConventionsNaming Conventions Variables and method names: Variables and method names:
Use lowercase. If the name consists Use lowercase. If the name consists of several words, concatenate all in of several words, concatenate all in one, use lowercase for the first word, one, use lowercase for the first word, and capitalize the first letter of each and capitalize the first letter of each subsequent word in the name. For subsequent word in the name. For example, the variables example, the variables radiusradius and and areaarea, and the method , and the method computeAreacomputeArea. .
Naming Conventions, cont.Naming Conventions, cont.
Class names:Class names: Capitalize the first letter of each Capitalize the first letter of each
word in the name. For example, word in the name. For example, the class name the class name TestComputeAreaTestComputeArea..
Constants: Constants: Capitalize all letters in constants. Capitalize all letters in constants.
For example, the constant For example, the constant PIPI..
Chapter 2 ExamplesChapter 2 Examples
ComputeArea (Listing 2.1, p27)ComputeArea (Listing 2.1, p27) TestScanner (Listing 2.6, p45)TestScanner (Listing 2.6, p45) ComputeLoan (Listing 2.7, p46)ComputeLoan (Listing 2.7, p46) ComputeChange (Listing 2.8, p48)ComputeChange (Listing 2.8, p48) ShowCurrentTime (Listing 2.9, p50)ShowCurrentTime (Listing 2.9, p50) ComputeLoanUsingInputDialog (Listing ComputeLoanUsingInputDialog (Listing
2.10, p57)2.10, p57)
Putting it all together: Listing Putting it all together: Listing 2.12.1
(available from Liang Code (available from Liang Code Samples)Samples)
Putting it all together: Listing Putting it all together: Listing 2.12.1
Variable declarations
Assignment of literal value into variable
Arithmetic expression and assignment
Output with concatenated data values.
A method CallA method Call
System.out.println("The area for the circle of radius " System.out.println("The area for the circle of radius " + radius + " is " + area); + radius + " is " + area);
The member variable (out) is an instance of another class (called PrintStream)
This method does not return a valueno assignment
The System class…this contains static member variable (out).
The name (identifier) of the member variable
PrintStream has a non-static (instance-specific) method called println
The arguments passed to the println method
About the System ClassAbout the System Class
Part of the Java Class LibraryPart of the Java Class Library Useful for standard input Useful for standard input
(keyboard) and output (screen) (keyboard) and output (screen) in console-based applicationsin console-based applications
More details from Sun’s Java More details from Sun’s Java documentation site:documentation site: http://java.sun.com/javase/6/docs/a
pi/
Putting it all together: Listing Putting it all together: Listing 2.12.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 Listing 2.10 ComputeLoanUsingInputDialogComputeLoanUsingInputDialog
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 Listing 2.10 ComputeLoanUsingInputDialogComputeLoanUsingInputDialog
Input from user and convert to appropriate data type.
User Input via JOptionPane User Input via JOptionPane ObjectObject
JOptionPaneJOptionPane is a class in the Java is a class in the Java class library that can display an input class library that can display an input dialog for obtaining user input or dialog for obtaining user input or show message dialogs for display to show message dialogs for display to the user.the user. Two methods:Two methods:
showInputDialogshowInputDialog – for user input – for user input showMessageDialogshowMessageDialog – for displaying a – for displaying a
message to the usermessage to the user
String annualInterestRateString = JOptionPane.showInputDialog( "Enter yearly interest rate, for example 8.25:");
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.
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
In this case, the variable nnualInterestRateString will contain the string “5.8”.
String annualInterestRateString = JOptionPane.showInputDialog( "Enter yearly interest rate, for example 8.25:");
Listing 2.10 Listing 2.10 ComputeLoanUsingInputDialogComputeLoanUsingInputDialog
Simple arithmetic expressions and assignments. NOTE: variables are declared and initialized in one statement.
Listing 2.10 Listing 2.10 ComputeLoanUsingInputDialogComputeLoanUsingInputDialog
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 Anatomy of an arithmetic statement involving castinginvolving casting
(assume that monthlyPayment had been calculated as 1525.875)
152587.5 (1)
1525.87 (3)Assign into variable monthlyPayment (4)
152587 (2)Casting from double to int truncates
Listing 2.10 Listing 2.10 ComputeLoanUsingInputDialogComputeLoanUsingInputDialog
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 Anatomy of a Complex Arithmetic ExpressionExpression
1) Declare the variable
2) Performcalculation
3) Performcalculation
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
7) Do the multiplication and division
8) Assign results to monthlyPayment
About the Math ClassAbout the Math Class
Part of the Java Class LibraryPart of the Java Class Library Contains methods for performing basic Contains methods for performing basic
numeric operations such as numeric operations such as exponentiation, logarithm, square exponentiation, logarithm, square root, and trigonometric functions. root, and trigonometric functions.
More details from Sun’s Java More details from Sun’s Java documentation site:documentation site: http://java.sun.com/j2se/1.5.0/docs/api
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();
The The ScannerScanner Class ClassAnother way to do User InputAnother way to do User Input
Listing 2.6 TestScannerListing 2.6 TestScannerIf 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 TestScannerListing 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 TestScannerListing 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 How Scanner-based User I/O looks in NetBeansNetBeans
System.out.print and System.out.println sends standard output to Output window, and the Scanner reads from the same window
Summary: Summary: User Input/Output OptionsUser Input/Output Options
Standard I/O StreamsStandard I/O Streams Input: Scanner class and methodsInput: Scanner class and methods Output: System.out.print (or println)Output: System.out.print (or println)
GUI (popup dialogs)GUI (popup dialogs) Input: JOptionPane.ShowInputDialogInput: JOptionPane.ShowInputDialog Output: Output:
JOptionPane.ShowMessageDialogJOptionPane.ShowMessageDialog Many more GUI options…we’ll study Many more GUI options…we’ll study
later in semesterlater in semester