programming fundamentals i (cosc- 1336), lecture 2 (prepared after chapter 2 of liang’s 2011...
Post on 13-Jan-2016
225 Views
Preview:
TRANSCRIPT
Programming Fundamentals I (COSC-1336), Lecture 2 (prepared after Chapter 2 of Liang’s 2011 textbook)Stefan Andrei
04/21/23 1COSC-1336, Lecture 2
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).
04/21/23 2COSC-1336, Lecture 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.
04/21/23 3COSC-1336, Lecture 2
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).
04/21/23 4COSC-1336, Lecture 2
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).
04/21/23 5COSC-1336, Lecture 2
Introducing Programming with an Example
Listing 2.1. Computing the Area of a Circle
This program computes the area of the circle.
04/21/23 6COSC-1336, Lecture 2
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // 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); }}
no valueradius
allocate memory for radius
animation
04/21/23 7COSC-1336, Lecture 2
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // 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); }}
no valueradius
memory
no valuearea
allocate memory for area
animation
04/21/23 8COSC-1336, Lecture 2
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // 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); }}
20radius
no valuearea
assign 20 to radius
animation
04/21/23 9COSC-1336, Lecture 2
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // 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); }}
20radius
memory
1256.636area
compute area and assign it to variable area
animation
04/21/23 10COSC-1336, Lecture 2
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // 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); }}
20radius
memory
1256.636area
print a message to the console
animation
04/21/23 11COSC-1336, Lecture 2
Reading Input from the Console1. 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();
04/21/23 12COSC-1336, Lecture 2
ComputeAreaWithConsoleInput.javaimport 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);
}
}
04/21/23 13COSC-1336, Lecture 2
Compiling and running ComputeAreaWithConsoleInput.java
04/21/23 14COSC-1336, Lecture 2
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, ornull.
An identifier can be of any length.
04/21/23 15COSC-1336, Lecture 2
Variables// Compute the first arearadius = 1.0;area = radius * radius * 3.14159;System.out.println("The area is " + area + " for radius "+radius);
// Compute the second arearadius = 2.0;area = radius * radius * 3.14159;System.out.println("The area is " + area + " for radius "+radius);
04/21/23 16COSC-1336, Lecture 2
Declaring Variables
int x; // Declare x to be an // integer variable;
double radius; // Declare radius to // be a double variable;
char a; // Declare a to be a // character variable;
04/21/23 17COSC-1336, Lecture 2
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
04/21/23 18COSC-1336, Lecture 2
Declaring and Initializing in One Step int x = 1;
double d = 1.4;
04/21/23 19COSC-1336, Lecture 2
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;
04/21/23 20COSC-1336, Lecture 2
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 64-bit signed (i.e., -9223372036854775808 to 9223372036854775807)
float Negative range: 32-bit IEEE 754 -3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754 -1.7976931348623157E+308 to -4.9E-324 Positive range: 4.9E-324 to 1.7976931348623157E+308
04/21/23 21COSC-1336, Lecture 2
Binary, Octal, and Hexadecimal Bases Decimal base is the one we used every day:
{0, 1, …, 9} Binary base: {0, 1}
Examples: 1101(2) = 1*23+1*22+0*21+1*20=13(10)
Octal base: {0, 1, …, 7} 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)
04/21/23 22COSC-1336, Lecture 2
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
04/21/23 23COSC-1336, Lecture 2
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2
5.0 / 2 yields a double value 2.5
5f / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
04/21/23 24COSC-1336, Lecture 2
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?
04/21/23 25COSC-1336, Lecture 2
Remainder Operator: Solution of the Exercise You can find that day is Tuesday using the following expression:
04/21/23 26COSC-1336, Lecture 2
Calculating time and display it Write a program that obtains hours and
minutes from seconds.
04/21/23 27COSC-1336, Lecture 2
Calculating hours and minutesimport 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");
}
}
04/21/23 28COSC-1336, Lecture 2
Editing, compiling, and running DisplayTime.java
04/21/23 29COSC-1336, Lecture 2
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.
04/21/23 30COSC-1336, Lecture 2
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.
04/21/23 31COSC-1336, Lecture 2
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;
04/21/23 32COSC-1336, Lecture 2
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.
04/21/23 33COSC-1336, Lecture 2
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).
04/21/23 34COSC-1336, Lecture 2
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.
04/21/23 35COSC-1336, Lecture 2
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
04/21/23 36COSC-1336, Lecture 2
Arithmetic Expressions
)94
(9))(5(10
5
43
y
x
xx
cbayx
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
04/21/23 37COSC-1336, Lecture 2
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 3 + 16 + 35 – 1 19 + 35 – 1 54 - 1 53
(1) inside parentheses first
(2) multiplication
(3) multiplication
(4) addition
(6) subtraction
(5) addition
04/21/23 38COSC-1336, Lecture 2
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:
)32)(( 95 fahrenheitcelsius
04/21/23 39COSC-1336, Lecture 2
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");
}
}
04/21/23 40COSC-1336, Lecture 2
Compiling and running FahrenheitToCelsius.java
04/21/23 41COSC-1336, Lecture 2
Shortcut Assignment Operators
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
X op= Y; is equivalent to X = X op (Y);
04/21/23 42COSC-1336, Lecture 2
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 ?
04/21/23 43COSC-1336, Lecture 2
Increment and Decrement Operators
Operator Name Description++var preincrement The expression (++var)
increments var by 1 and evaluates to the new value in
var after the increment.var++ postincrement The expression (var++) evaluates
to the original value in var and
increments var by 1. --var predecrement The expression (--var)
decrements var by 1 and evaluates to the new value in
var after the decrement. var-- postdecrement The expression (var--) evaluates
to the original value in var and decrements var by 1.
04/21/23 44COSC-1336, Lecture 2
Increment and Decrement Operators (cont.)
int i = 10; int newNum = 10 * i++;
int newNum = 10 * i; i = i + 1;
Same effect as
int i = 10; int newNum = 10 * (++i);
i = i + 1; int newNum = 10 * i;
Same effect as
04/21/23 45COSC-1336, Lecture 2
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;
04/21/23 46COSC-1336, Lecture 2
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 count = 2;
int x = ++count; How much is x and
count? The value of x is 3 and
the value of count is 3.
int count1 = 2, count2 = 3;
int x = count1++ + ++count2; How much is x, count1, and
count2? The value of x is 6 and the values
of count1 and count2 are 3 and 4.int count1 = 2, count2 = 3;
int x = count1++ + count2++; How much is x? The value of x is 5 and the values
of count1 and count2 are 3 and 4.
04/21/23 47COSC-1336, Lecture 2
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
04/21/23 48COSC-1336, Lecture 2
Conversion Rules When performing a binary operation involving
two operands of different types, Java automatically converts the operand based on the following rules:
1. If one of the operands is double, the other is converted into double.
2. Otherwise, if one of the operands is float, the other is converted into float.
3. Otherwise, if one of the operands is long, the other is converted into long.
4. Otherwise, both operands are converted into int.
04/21/23 49COSC-1336, Lecture 2
Type Casting Implicit casting: double d = 3; // type widening
Explicit casting: int i = (int)3.0; // type narrowing int i = (int)3.9; // Fraction part is // truncated What is wrong? int x = 5 / 2.0;
byte, short, int, long, float, double
range increases
04/21/23 50COSC-1336, Lecture 2
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 !
04/21/23 51COSC-1336, Lecture 2
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
04/21/23 52COSC-1336, Lecture 2
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!
04/21/23 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.
04/21/23 54COSC-1336, Lecture 2
Problem: Displaying Unicodes Write a program that displays two Chinese characters and three Greek letters.
04/21/23 55COSC-1336, Lecture 2
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);
}
}
04/21/23 56COSC-1336, Lecture 2
Compiling and running DisplayUnicode.java
04/21/23 57COSC-1336, Lecture 2
Character Data Type
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
Four hexadecimal digits.
04/21/23 58COSC-1336, Lecture 2
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);
04/21/23 59COSC-1336, Lecture 2
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;
04/21/23 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);
04/21/23 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);
04/21/23 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;
04/21/23 63COSC-1336, Lecture 2
Escape Sequences for Special CharactersDescription Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
04/21/23 64COSC-1336, Lecture 2
Appendix B: ASCII Character SetASCII Character Set is a subset of the Unicode from \u0000 to \
u007f
04/21/23 65COSC-1336, Lecture 2
ASCII Character Set, cont. The ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
04/21/23 66COSC-1336, Lecture 2
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.
04/21/23 67COSC-1336, Lecture 2
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.
04/21/23 68COSC-1336, Lecture 2
String Concatenation // Three strings are concatenatedString message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character BString s1 = "Supplement" + 'B'; // s1 becomes SupplementB
04/21/23 69COSC-1336, Lecture 2
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.
04/21/23 70COSC-1336, Lecture 2
More on the ‘+’ semantics Operand1 + Operand2 + Operand3 =
(Operand1 + Operand2) + Operand3 Example:
"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"
04/21/23 71COSC-1336, Lecture 2
Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles
04/21/23 72COSC-1336, Lecture 2
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.
04/21/23 73COSC-1336, Lecture 2
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().
04/21/23 74COSC-1336, Lecture 2
Naming Conventions (cont.) Class names:
Capitalize the first letter of each word in the name. For example, the class name ComputeArea.
Constants: Capitalize all letters in constants, and use underscores
to connect words. For example, PI and MAX_VALUE are good names for
constants.
04/21/23 75COSC-1336, Lecture 2
Proper Indentation and Spacing Indentation
Indent two spaces.
Spacing Use blank line to separate segments of the code.
04/21/23 76COSC-1336, Lecture 2
Block Styles
Use end-of-line style for braces.
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"); } }
End-of-line style
Next-line style
04/21/23 77COSC-1336, Lecture 2
Programming Errors
Syntax Errors Detected by the compiler
Runtime Errors Causes the program to abort
Logic Errors Produces incorrect result
Question: Which of the errors are considered the most dangerous?
04/21/23 78COSC-1336, Lecture 2
Syntax Errors – can you find it?public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); }}
04/21/23 79COSC-1336, Lecture 2
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;
}
}
04/21/23 80COSC-1336, Lecture 2
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);
}
}
04/21/23 81COSC-1336, Lecture 2
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.
04/21/23 82COSC-1336, Lecture 2
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.
04/21/23 83COSC-1336, Lecture 2
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.
04/21/23 84COSC-1336, Lecture 2
The JOptionPane Input
This lesson provides two ways of obtaining input:
1. Using the Scanner class (console input)
2. Using JOptionPane input dialogs
04/21/23 85COSC-1336, Lecture 2
Getting Input from Input Dialog Boxes String input = JOptionPane.showInputDialog(
"Enter an input");
04/21/23 86COSC-1336, Lecture 2
Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog(
null, "Enter a year", "Example 2.2 Input",
JOptionPane.QUESTION_MESSAGE);
04/21/23 87COSC-1336, Lecture 2
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.
04/21/23 88COSC-1336, Lecture 2
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.
04/21/23 89COSC-1336, Lecture 2
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".
04/21/23 90COSC-1336, Lecture 2
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".
04/21/23 91COSC-1336, Lecture 2
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).
04/21/23 92COSC-1336, Lecture 2
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).
04/21/23 93COSC-1336, Lecture 2
Reading suggestions
From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, 0132130807]
Chapter 2 (Elementary Programming)
04/21/23 94COSC-1336, Lecture 2
Coming up next
From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, 0132130807] Chapter 3 (Selections)
04/21/23 95COSC-1336, Lecture 2
Thank you for your attention!
Questions?
04/21/23 96COSC-1336, Lecture 2
top related