Download lecture2

Document related concepts
no text concepts found
Transcript
Programming Fundamentals I (COSC1336),
Lecture 2 (prepared after Chapter 2 of
Liang’s 2011 textbook)
Stefan Andrei
5/24/2017
COSC-1336, Lecture 2
1
Overview of the previous lecture








To review computer basics, programs, and
operating systems (§§1.2-1.4).
To explore the relationship between Java and the
World Wide Web (§1.5).
To distinguish the terms API, IDE, and JDK (§1.6).
To write a simple Java program (§1.7).
To display output on the console (§1.7).
To explain the basic syntax of a Java program
(§1.7).
To create, compile, and run Java programs (§1.8).
(GUI) To display output using the JOptionPane
output dialog boxes (§1.9).
5/24/2017
COSC-1336, Lecture 2
2
Connection with current lecture



In the preceding chapter, you learned how to
create, compile, and run a Java program.
Starting from this chapter, you will learn how
to solve practical problems programmatically.
Through these problems, you will learn Java
primitive data types and related subjects,
such as variables, constants, data types,
operators, expressions, and input and output.
5/24/2017
COSC-1336, Lecture 2
3
Overview of This Lecture









To write Java programs to perform simple calculations
(§2.2).
To obtain input from the console using the Scanner class
(§2.3).
To use identifiers to name variables, constants, methods,
and classes (§2.4).
To use variables to store data (§§2.5-2.6).
To program with assignment statements and assignment
expressions (§2.6).
To use constants to store permanent data (§2.7).
To declare Java primitive data types: byte, short, int,
long, float, double, and char (§§2.8.1).
To use Java operators to write numeric expressions
(§§2.8.2–2.8.3).
To display current time (§2.9).
5/24/2017
COSC-1336, Lecture 2
4
Overview of This Lecture (cont)









To use short hand operators (§2.10).
To cast value of one type to another type (§2.11).
To compute loan payment (§2.12).
To represent characters using the char type (§2.13).
To compute monetary changes (§2.14).
To represent a string using the String type (§2.15).
To become familiar with Java documentation,
programming style, and naming conventions
(§2.16).
To distinguish syntax errors, runtime errors, and
logic errors and debug errors (§2.17).
(GUI) To obtain input using the JOptionPane input
dialog boxes (§2.18).
5/24/2017
COSC-1336, Lecture 2
5
Introducing Programming with an
Example

Listing 2.1. Computing the Area of a Circle

This program computes the area of the
circle.
5/24/2017
COSC-1336, Lecture 2
6
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
double radius;
double area;
allocate memory
for radius
radius
no value
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
5/24/2017
COSC-1336, Lecture 2
7
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
double radius;
double area;
// Assign a radius
radius = 20;
memory
radius
no value
area
no value
allocate memory
for area
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
5/24/2017
COSC-1336, Lecture 2
8
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
double radius;
double area;
assign 20 to radius
radius
area
20
no value
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
5/24/2017
COSC-1336, Lecture 2
9
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
double radius;
double area;
memory
radius
area
20
1256.636
// Assign a radius
radius = 20;
compute area and assign
it to variable area
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
5/24/2017
COSC-1336, Lecture 2
10
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
double radius;
double area;
memory
radius
area
20
1256.636
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
print a message to the
console
// Display results
System.out.println("The area for the circle of radius "
+ radius + " is " + area);
}
}
5/24/2017
COSC-1336, Lecture 2
11
Reading Input from the Console
1. Create a Scanner object
Scanner input = 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 input = new Scanner(System.in);
double d = input.nextDouble();
5/24/2017
COSC-1336, Lecture 2
12
ComputeAreaWithConsoleInput.java
import java.util.Scanner;
// Scanner is in the java.util package
public class ComputeAreaWithConsoleInput {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);
// Prompt the user to enter a radius
System.out.print("Enter a number for radius:");
double radius = input.nextDouble();
double area = radius * radius * 3.14159;
System.out.println("Area of circle of radius " +
radius + " is " + area);
}
}
5/24/2017
COSC-1336, Lecture 2
13
Compiling and running
ComputeAreaWithConsoleInput.java
5/24/2017
COSC-1336, Lecture 2
14
Identifiers


An identifier is a sequence of characters that
consist of letters, digits, underscores (_), and dollar
signs ($).
An identifier must start with a letter, an underscore
(_), or a dollar sign ($). It cannot start with a digit.



An identifier cannot be a reserved word. (See Appendix
A, “Java Keywords,” for a list of reserved words).
An identifier cannot be true, false, or
null.
An identifier can be of any length.
5/24/2017
COSC-1336, Lecture 2
15
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is " + area +
" for radius "+radius);
// Compute the second area
radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is " + area +
" for radius "+radius);
5/24/2017
COSC-1336, Lecture 2
16
Declaring Variables
int x;
// Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a;
5/24/2017
// Declare a to be a
// character variable;
COSC-1336, Lecture 2
17
Assignment Statements
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
5/24/2017
COSC-1336, Lecture 2
18
Declaring and Initializing in One Step

int x = 1;

double d = 1.4;
5/24/2017
COSC-1336, Lecture 2
19
Constants
The general syntax of declaring and defining a constant is:
final <datatype> <CONSTANT_NAME> = <value>;
where final is the modifier, <datatype> is the data type
of the constant , <CONSTANT_NAME> is the name of the
constant (it is recommended to be with capital letters), and
<value> is its value (which of course, it cannot be
modified).



Example:
final double PI = 3.14159;
final int SIZE = 3;
5/24/2017
COSC-1336, Lecture 2
20
Numerical Data Types
Name
Range
Storage Size
byte
–27 (-128) to 27–1 (127)
8-bit signed
short
–215 (-32768) to 215–1 (32767)
16-bit signed
int
–231 (-2147483648) to 231–1 (2147483647) 32-bit signed
long
–263 to 263–1
(i.e., -9223372036854775808
to 9223372036854775807)
64-bit signed
float
Negative range:
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
32-bit IEEE 754
double
Negative range:
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
64-bit IEEE 754
5/24/2017
COSC-1336, Lecture 2
21
Binary, Octal, and Hexadecimal Bases


Decimal base is the one we used every day:
{0, 1, …, 9}
Binary base: {0, 1}


Octal base: {0, 1, …, 7}


Examples: 1101(2) = 1*23+1*22+0*21+1*20=13(10)
Example: 352(8) = 3*82+5*81+2*80=234(10)
Hexadecimal base: {0, …, 9, A, B, C, D, E, F}


Where A means 10(10), B means 11(10), …, F means
15(10).
Example: 4BE(16) = 4*162+11*161+14*160=1214(10)
5/24/2017
COSC-1336, Lecture 2
22
Numeric Operators
Name
Meaning
Example
Result
+
Addition
34 + 1
35
-
Subtraction
34.0 – 0.1
33.9
*
Multiplication
300 * 30
9000
/
Division
1.0 / 2.0
0.5
%
Remainder
20 % 3
2
5/24/2017
COSC-1336, Lecture 2
23
Integer Division
+, -, *, /, and %
5 / 2
yields an integer 2
5.0 / 2
5f / 2
5 % 2
5/24/2017
yields a double value 2.5
yields a double value 2.5
yields 1 (the remainder of the division)
COSC-1336, Lecture 2
24
Remainder Operator

Remainder is very useful in programming.

For example:

an even number % 2 is always 0 and

an odd number % 2 is always 1.
So you can use this property to determine whether a
number is even or odd.


Exercise:
Suppose today is Saturday and you and your friends are going
to meet in 10 days.


What day is in 10 days?
5/24/2017
COSC-1336, Lecture 2
25
Remainder Operator: Solution of the
Exercise
You can find that day is Tuesday using the
following expression:

5/24/2017
COSC-1336, Lecture 2
26
Calculating time and display it

Write a program that obtains hours and
minutes from seconds.
5/24/2017
COSC-1336, Lecture 2
27
Calculating hours and minutes
import java.util.Scanner;
public class DisplayTime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer for seconds:");
int seconds = input.nextInt();
int minutes = seconds / 60;
int remainingSeconds = seconds % 60;
System.out.println(seconds + " seconds is " +
minutes + " minutes and " +
remainingSeconds + " seconds");
}
}
5/24/2017
COSC-1336, Lecture 2
28
Editing, compiling, and running
DisplayTime.java
5/24/2017
COSC-1336, Lecture 2
29
Problem: Displaying Current Time

The currentTimeMillis() method in the System
class returns the current time in milliseconds since
the midnight, January 1, 1970 GMT.

1970 was the year when the Unix operating system
was formally introduced.

This method can be similarly used to obtain the
current time, and then compute the current second,
minute, and hour.
5/24/2017
COSC-1336, Lecture 2
30
Note
Calculations involving floating-point numbers are
approximated because these numbers are not stored with
complete accuracy.


Example:
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);

displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);

displays 0.09999999999999998, not 0.1.

Integers are stored precisely.
Therefore, calculations with integers yield a precise integer
result.

5/24/2017
COSC-1336, Lecture 2
31
Number Literals
A literal is a constant value that appears
directly in the program.

For example, 34, 1,000,000, and 5.0 are
literals in the following statements:

int i = 34;
long x = 1000000;
double d = 5.0;
5/24/2017
COSC-1336, Lecture 2
32
Integer Literals
An integer literal can be assigned to an integer
variable as long as it can fit into the variable.

A compilation error would occur if the literal were
too large for the variable to hold.


For example, the statement
byte b = 1000;
would cause a compilation error, because 1000
cannot be stored in a variable of the byte type.

5/24/2017
COSC-1336, Lecture 2
33
Integer Literals (cont)




An integer literal is assumed to be of the int
type, whose value is between
-231 (-2147483648)
to
231–1 (2147483647).
To denote an integer literal of the long type,
append it with the letter L or l.
L is preferred because l (lowercase L) can
easily be confused with 1 (the digit one).
5/24/2017
COSC-1336, Lecture 2
34
Floating-Point Literals

Floating-point literals are written with a decimal point.
By default, a floating-point literal is treated as a double
type value.

For example, 5.0 is considered a double value, not a
float value.

You can make a number a float by appending the
letter f or F, and make a number a double by appending
the letter d or D.

For example, you can use 100.2f or 100.2F for a float
number, and 100.2d or 100.2D for a double number.

5/24/2017
COSC-1336, Lecture 2
35
Scientific Notation
Floating-point literals can also be specified in
scientific notation.

For example, 1.23456e+2, same as 1.23456e2,
is equivalent to 123.456, and 1.23456e-2 is
equivalent to 0.0123456.

The character E (or e) means actually 10 and
the value after E (or e) represents an exponent.


1.23456e+2 = 1.23456 * 102 = 123.456
5/24/2017
COSC-1336, Lecture 2
36
Arithmetic Expressions
3  4 x 10( y  5)( a  b  c)
4 9 x

 9( 
)
5
x
x
y
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
5/24/2017
COSC-1336, Lecture 2
37
How to Evaluate an Expression?
 Though Java has its own way to evaluate an expression
behind the scene, the result of a Java expression and its
corresponding arithmetic expression are the same.
 Therefore, you can safely apply the arithmetic rule for
evaluating a Java expression.
3 + 4 * 4 + 5 * (4 + 3) - 1
3 + 4 * 4 + 5 * 7 – 1
3 + 16 + 5 * 7 – 1
(1) inside parentheses first
(2) multiplication
(3) multiplication
3 + 16 + 35 – 1
19 + 35 – 1
54 - 1
53
5/24/2017
COSC-1336, Lecture 2
(4) addition
(5) addition
(6) subtraction
38
Problem: Converting Temperatures
Fahrenheit is the temperature scale proposed in 1724 by,
and named after, the Dutch-German-Polish physicist Daniel
Gabriel Fahrenheit (1686–1736).
 Today, the temperature scale has been replaced by the
Celsius scale in most countries, but it remains the official
scale of the United States and Belize and is retained as a
secondary scale in Canada.
 The Celsius scale is named after the Swedish astronomer
Anders Celsius (1701–1744), who developed a similar
temperature scale in 1742.
 Write a program that converts a Fahrenheit degree to
Celsius using the formula:

celsius  ( 95 )( fahrenheit  32)
5/24/2017
COSC-1336, Lecture 2
39
FahrenheitToCelsius.java
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a degree in Fahrenheit:");
double fahrenheit = input.nextDouble();
// Convert Fahrenheit to Celsius
double celsius = (5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit +
" is " + celsius + " in Celsius");
}
}
5/24/2017
COSC-1336, Lecture 2
40
Compiling and running
FahrenheitToCelsius.java
5/24/2017
COSC-1336, Lecture 2
41
Shortcut Assignment Operators
X op= Y;
5/24/2017
is equivalent to X
= X op (Y);
Operator Example
Equivalent
+=
i += 8
i = i + 8
-=
f -= 8.0
f = f - 8.0
*=
i *= 8
i = i * 8
/=
i /= 8
i = i / 8
%=
i %= 8
i = i % 8
COSC-1336, Lecture 2
42
Examples

Example 1:
int y = 5, x = 10;
x += y + 1;


How much is x ?
Example 2:
int y = 5, x = 10;
x *= y + 1;

How much is x ?
5/24/2017
COSC-1336, Lecture 2
43
Increment and Decrement Operators
Operator
++var
Name
preincrement
var++
postincrement
--var
predecrement
var--
postdecrement
original
5/24/2017
Description
The expression (++var) increments var by 1
and evaluates to the new value in var after the
increment.
The expression (var++) evaluates to the
original value in var and increments var by 1.
The expression (--var) decrements var by 1
and evaluates to the new value in var after the
decrement.
The expression (var--) evaluates to the
value in var and decrements var by 1.
COSC-1336, Lecture 2
44
Increment and Decrement Operators
(cont.)
int i = 10;
int newNum = 10 * i++;
Same effect as
int i = 10;
int newNum = 10 * (++i);
Same effect as
5/24/2017
int newNum = 10 * i;
i = i + 1;
COSC-1336, Lecture 2
i = i + 1;
int newNum = 10 * i;
45
Increment and Decrement Operators
(cont.)
 Using increment and decrement operators
makes expressions short, but it also makes
them complex and difficult to read.
 Avoid using these operators in expressions
that modify multiple variables, or the same
variable for multiple times such as this:
int k = ++i + i;
5/24/2017
COSC-1336, Lecture 2
46
Increment and Decrement (cont)
int count = 2;
int x = count++;


How much is x and
count?
The value of x is 2 and
the value of count is 3.
int count1 = 2, count2 = 3;
int x = count1++ + ++count2;


int count1 = 2, count2 = 3;
int x = count1++ + count2++;
int count = 2;
int x = ++count;


How much is x and

count?

The value of x is 3 and
the value of count is 3.
5/24/2017
How much is x, count1, and
count2?
The value of x is 6 and the values
of count1 and count2 are 3 and 4.
How much is x?
The value of x is 5 and the values
of count1 and count2 are 3 and 4.
COSC-1336, Lecture 2
47
Numeric Type Conversion

Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
5/24/2017
COSC-1336, Lecture 2
48
Conversion Rules

1.
2.
3.
4.
When performing a binary operation involving
two operands of different types, Java
automatically converts the operand based on the
following rules:
If one of the operands is double, the other is
converted into double.
Otherwise, if one of the operands is float, the
other is converted into float.
Otherwise, if one of the operands is long, the
other is converted into long.
Otherwise, both operands are converted into int.
5/24/2017
COSC-1336, Lecture 2
49
Type Casting

Implicit casting:
double d = 3; // type widening

Explicit casting:
int i = (int)3.0;
int i = (int)3.9;

What is wrong?

int x = 5 / 2.0;
// type narrowing
// Fraction part is
// truncated
range increases
byte, short, int, long, float, double
5/24/2017
COSC-1336, Lecture 2
50
Highlighting casting

The following Java statements:
double x = 3.45;
int a = x;


will lead to a compile-time error (“found double,
required int”).
However, we can use cast to avoid the error, but:
double x = 3.45;
int a = (int) x;

Precision will be lost !
5/24/2017
COSC-1336, Lecture 2
51
More examples on casting



if total and count are doubles, and we want
an integer result when dividing them, we can
cast to int.
The result will be loss of precision.
For example:
double total = 8.20;
double count = 3.20;
int result = (int) (total / count);

How much is result?

2
5/24/2017
COSC-1336, Lecture 2
52
The Unicode Consortium



Java characters use Unicode.
Originally, Unicode used a 16-bit encoding
scheme established by the Unicode
Consortium to support the interchange,
processing, and display of written texts in the
world’s diverse languages (65,536 characters).
Later, the Unicode standard has been
extended to 1,112,064 characters – beyond
the scope of this course!
5/24/2017
COSC-1336, Lecture 2
53
Unicode Format
 The standard Unicode takes two bytes, preceded
by \u, expressed in four hexadecimal numbers that
run from '\u0000' to '\uFFFF'.
 So, the standard Unicode can represent 65535
+
1 characters.
Unicode \u03b1 \u03b2 \u03b3 for three
Greek letters.
5/24/2017
COSC-1336, Lecture 2
54
Problem: Displaying Unicodes
Write a program that displays two Chinese
characters and three Greek letters.

5/24/2017
COSC-1336, Lecture 2
55
DisplayUnicode.java
import javax.swing.JOptionPane;
public class DisplayUnicode {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,
"\u6B22\u8FCE \u03b1 \u03b2 \u03b3",
"\u6B22\u8FCE Welcome",
JOptionPane.INFORMATION_MESSAGE);
}
}
5/24/2017
COSC-1336, Lecture 2
56
Compiling and running
DisplayUnicode.java
5/24/2017
COSC-1336, Lecture 2
57
Character Data Type
Four hexadecimal
digits.
(ASCII)
'4'; (ASCII)
char letter = 'A';
char numChar =
char letter = '\u0041';
(Unicode)
char numChar = '\u0034';
5/24/2017
(Unicode)
COSC-1336, Lecture 2
58
More on ASCII and Unicode



The ASCII character set (American Standard Code
Information Interchange) is older and smaller than
Unicode, but is still quite popular.
NOTE: The increment and decrement operators can
also be used on char variables to get the next or
preceding Unicode character.
For example, the below statements display character b.
char ch = 'a';
System.out.println(++ch);
5/24/2017
COSC-1336, Lecture 2
59
More about numeric operators and chars



The other numeric operators cannot be directly
used to get a char (like for ++ and -- operators).
A char operand is automatically cast to a
number if the other operand is a number or a
char.
Example: the below code will lead to a syntax
error as there is no ‘+’ operator for char type.
char x = '2';
char y = '0';
char z = x + y;
5/24/2017
COSC-1336, Lecture 2
60
More on ‘+’ operator for chars

To fix the previous error, we can cast the obtained
number to a char.
char x = '2';
char y = '0';
char z = (char) (x + y);
System.out.println(z);


will display b
Question: What the below code will display?
char x = '2';
char y = '0';
char z = (char) x + y;
System.out.println(z);
5/24/2017
COSC-1336, Lecture 2
61
More on ‘+’ operator for chars (cont.)

How about the code?
char x = '2';
char y = '0';
char z = (char) x + (char) y;
System.out.println(z);

How about this?
int x = '2';
int y = '0';
int z = x + y;
System.out.println((char) z);
5/24/2017
COSC-1336, Lecture 2
62
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
5/24/2017
COSC-1336, Lecture 2
63
Escape Sequences for Special Characters
Description
Escape Sequence
Unicode
Backspace
\b
\u0008
Tab
\t
\u0009
Linefeed
\n
\u000A
Carriage return \r
\u000D
Backslash
\\
\u005C
Single Quote
\'
\u0027
Double Quote
\"
\u0022
5/24/2017
COSC-1336, Lecture 2
64
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to
\u007f
5/24/2017
COSC-1336, Lecture 2
65
ASCII Character Set, cont.
 The ASCII Character Set is a subset of the Unicode from
\u0000 to \u007f
5/24/2017
COSC-1336, Lecture 2
66
The String Type
 The char type only represents one character.
 To represent a string of characters, use the data type
called String.
 For example,
String message = "Welcome to Java";
 String is actually a predefined class in the Java library
just like the System class and JOptionPane class.
 The String type is not a primitive type.
 It is known as a reference type.
5/24/2017
COSC-1336, Lecture 2
67
The String Type (cont.)



Any Java class can be used as a reference type for a
variable.
Reference data types will be thoroughly discussed in
Chapter 7, “Objects and Classes.”
For the time being, you just need to know how to
declare a String variable, how to assign a string to
the variable, and how to concatenate strings.
5/24/2017
COSC-1336, Lecture 2
68
String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
5/24/2017
COSC-1336, Lecture 2
69
2.1 – String Concatenation





The + operator is also used for arithmetic
addition.
The function that it performs depends on the
type of the information on which it operates.
If both operands are Strings, or if one is a
String and one is a number, it performs String
concatenation.
If both operands are numeric, it adds them.
The + operator is evaluated left to right, but
parentheses can be used to force the order.
5/24/2017
COSC-1336, Lecture 2
70
More on the ‘+’ semantics


Operand1 + Operand2 + Operand3 =
(Operand1 + Operand2) + Operand3
Example:







5/24/2017
"Maes " + 107 + 111 = ("Maes " + 107) + 111
Since "Maes " is of type String and 107 is of type int,
then 107 is converted to a String.
Hence ("Maes " + 107) + 111 = "Maes 107 " + 111
This is equal to "Maes 107111"
107 + 111 + " Maes" = (107 + 111) + " Maes"
Since both 107 and 111 are of type int, there is no need
for any conversion, thus the answer is 218.
Hence (107 + 111) + " Maes" = "218 Maes"
COSC-1336, Lecture 2
71
Programming Style and Documentation




Appropriate Comments
Naming Conventions
Proper Indentation and Spacing Lines
Block Styles
5/24/2017
COSC-1336, Lecture 2
72
Appropriate Comments


Include a summary at the beginning of the
program to explain what the program does, its
key features, its supporting data structures,
and any unique techniques it uses.
Include your name, class section, instructor,
date, and a brief description at the beginning of
the program.
5/24/2017
COSC-1336, Lecture 2
73
Naming Conventions


Choose meaningful and descriptive names.
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().
5/24/2017
COSC-1336, Lecture 2
74
Naming Conventions (cont.)

Class names:



Capitalize the first letter of each word in the name.
For example, the class name ComputeArea.
Constants:


5/24/2017
Capitalize all letters in constants, and use underscores
to connect words.
For example, PI and MAX_VALUE are good names for
constants.
COSC-1336, Lecture 2
75
Proper Indentation and Spacing

Indentation


Indent two spaces.
Spacing

5/24/2017
Use blank line to separate segments of the code.
COSC-1336, Lecture 2
76
Block Styles

Use end-of-line style for braces.
Next-line
style
public class Test
{
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
5/24/2017
COSC-1336, Lecture 2
End-of-line
style
77
Programming Errors

Syntax Errors


Runtime Errors


Causes the program to abort
Logic Errors


Detected by the compiler
Produces incorrect result
Question: Which of the errors
considered the most dangerous?
5/24/2017
COSC-1336, Lecture 2
are
78
Syntax Errors – can you find it?
public class ShowSyntaxErrors {
public static void main(String[] args) {
i = 30;
System.out.println(i + 4);
}
}
5/24/2017
COSC-1336, Lecture 2
79
Runtime Errors – can you find it?
import java.util.Scanner;
public class ShowRuntimeErrors {
public static void main(String[] args) {
System.out.print("Enter an integer: ");
Scanner input = new Scanner(System.in);
int d = input.nextInt();
int i = 1 / d;
}
}
5/24/2017
COSC-1336, Lecture 2
80
Logic Errors – can you find it?
import javax.swing.JOptionPane;
public class ShowLogicErrors {
// Determine if a number is between 1 and 100 inclusively
public static void main(String[] args) {
// Prompt the user to enter a number
String input = JOptionPane.showInputDialog(null,
"Please enter an integer:",
"ShowLogicErrors", JOptionPane.QUESTION_MESSAGE);
int number = Integer.parseInt(input);
System.out.println("The number is between 1 and 100, " +
"inclusively? " + ((1 < number) && (number < 100)));
System.exit(0);
}
}
5/24/2017
COSC-1336, Lecture 2
81
Debugging
Logic errors are called ‘bugs’.
 The process of finding and correcting errors is
called debugging.
 A common approach to debugging is to use a
combination of methods to narrow down to the part
of the program where the bug is located.

5/24/2017
COSC-1336, Lecture 2
82
Debugging (cont.)

You can hand-trace the program in order to show
the values of the variables or the execution flow
of the program:




You can catch errors by reading the program, or
You can insert print() statements (spies).
This approach might work for a short, simple
program.
But for a large, complex program, the most
effective approach for debugging is to use a
debugger utility.
5/24/2017
COSC-1336, Lecture 2
83
Debugger
A debugger is a program that facilitates
debugging.
 You can use a debugger to:

Execute a single statement at a time.
 Trace into or stepping over a method.
 Set breakpoints.
 Display variables.
 Display call stack.
 Modify variables.

5/24/2017
COSC-1336, Lecture 2
84
The JOptionPane Input

1.
2.
This lesson provides two ways of obtaining input:
Using the Scanner class (console input)
Using JOptionPane input dialogs
5/24/2017
COSC-1336, Lecture 2
85
Getting Input from Input Dialog Boxes
String input = JOptionPane.showInputDialog(
"Enter an input");
5/24/2017
COSC-1336, Lecture 2
86
Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog(
null, "Enter a year", "Example 2.2 Input",
JOptionPane.QUESTION_MESSAGE);
5/24/2017
COSC-1336, Lecture 2
87
Two Ways to Invoke the Method
There are several ways to use the showInputDialog()
method.
 For the time being, you only need to know two ways to
invoke it.
 One is to use a statement as shown in the example:

String string =
JOptionPane.showInputDialog(null, x,
y, JOptionPane.QUESTION_MESSAGE);
where x is a String for the prompting message, and y
is a String for the title of the input dialog box.

5/24/2017
COSC-1336, Lecture 2
88
The other way to invoke the method

The other is to use a statement like this:
JOptionPane.showInputDialog(x);
where x is a String for the prompting message.
5/24/2017
COSC-1336, Lecture 2
89
Converting Strings to ints
The input returned from the input dialog box is a
String.
 If you enter a numeric value such as 123, it returns
"123".
 To obtain the input as a number, you have to convert
a String into a number.
 To convert a String into an int value, you can use
the static parseInt() method in the Integer class as
follows:

int intValue = Integer.parseInt(intString);

where intString is a numeric String such as "123".
5/24/2017
COSC-1336, Lecture 2
90
Converting Strings to doubles
To convert a String into a double value, you can use
the static parseDouble() method in the Double class as
follows:

double doubleValue=Double.parseDouble(doubleString);
where doubleString is a numeric string such as
"23.45".

5/24/2017
COSC-1336, Lecture 2
91
Summary









To write Java programs to perform simple calculations
(§2.2).
To obtain input from the console using the Scanner class
(§2.3).
To use identifiers to name variables, constants, methods,
and classes (§2.4).
To use variables to store data (§§2.5-2.6).
To program with assignment statements and assignment
expressions (§2.6).
To use constants to store permanent data (§2.7).
To declare Java primitive data types: byte, short, int,
long, float, double, and char (§§2.8.1).
To use Java operators to write numeric expressions
(§§2.8.2–2.8.3).
To display current time (§2.9).
5/24/2017
COSC-1336, Lecture 2
92
Summary (cont)









To use short hand operators (§2.10).
To cast value of one type to another type (§2.11).
To compute loan payment (§2.12).
To represent characters using the char type (§2.13).
To compute monetary changes (§2.14).
To represent a string using the String type (§2.15).
To become familiar with Java documentation,
programming style, and naming conventions
(§2.16).
To distinguish syntax errors, runtime errors, and
logic errors and debug errors (§2.17).
(GUI) To obtain input using the JOptionPane input
dialog boxes (§2.18).
5/24/2017
COSC-1336, Lecture 2
93
Reading suggestions

From [Liang: Introduction to Java programming:
Eight Edition, 2011 Pearson Education,
0132130807]
 Chapter 2 (Elementary Programming)
5/24/2017
COSC-1336, Lecture 2
94
Coming up next

From [Liang: Introduction to Java
programming: Eight Edition, 2011 Pearson
Education, 0132130807]

5/24/2017
Chapter 3 (Selections)
COSC-1336, Lecture 2
95
Thank you for your attention!
Questions?
5/24/2017
COSC-1336, Lecture 2
96