What We Will Cover
Continuations
Homework Questions?
Viewing WebCT Assignment Results
^ top
3.1: Numbers and Arithmetic
Objectives
At the end of the lesson the student will be able to:
- Distinguish between an integer and a floating-point number
- Explain what is meant by the term: expression
- Write code for arithmetic expressions
- Infer the type returned from a mixed-mode arithmetic expression
- Explain the term precedence
- Construct expressions that use mathematical methods
|
^ top
3.1.1: Literal Integers
- As we saw before, Java has two general types of numbers: integers and floating-point
- An integer is zero or any positive or negative number without a decimal point
- Some examples:
0 1 -1 +5 -27 1000 -128
These examples are known as literals because we write them just like we do normally
Literals are a type of constant data value in a program
Once you have coded the value into your program, there is no way to change it
Integer literals cannot have any commas, decimal points or special symbols (like a $) in them
However, they may have a sign (+ or -) before the number
The compiler saves these literal integer values as an int by default
Thus each of the above examples uses 4 bytes of memory storage
Using Literal Integers
- As we saw before, we can use literal integers for assignment of data to variables and constants
int yards = 4;
int number1 = 5, number2 = 10;
final int FEET_PER_YARD = 3;
Another use for literal integer is in arithmetic expressions
An expression is a part of a statement that returns a value
As an example:
int feet = yards * 3;
In the example above, yards * 3 is an expression
Before the program assigns a value to feet, it computes the product of yards * 3
The right hand side of an assignment statement is always an expression
The right hand side is always computed before assignment to the left hand side
^ top
3.1.2: Literal Floating-Point Numbers
- A floating-point number is any signed or unsigned number with a decimal point
- Some examples:
0.0 1.0 -1.1 +5. -6.3 3234.56 0.33
Note that 0.0, 1.0 and +5. are floating-point numbers, but could be rewritten as integers
Like integers, floating-point numbers cannot have any commas or special symbols
The compiler saves these literal floating-point values as a double by default
Thus each of the above examples uses 8 bytes of memory storage
Using Floating-Point Literals
- Like literal integers, we use literal floating-point numbers in assignment statements
double num = 1.23;
double area = 0.0, radius = 4.5;
final double PI = 3.14159623;
We also use them in arithmetic expressions, just like integers
area = radius * radius * 3.14159;
Exponential Notation
- Floating-point literals can be written in exponential notation
- Similar to scientific notation
- Used to express both very large and very small values in compact form
- For example:
| Decimal Notation |
Scientific Notation |
Exponential Notation |
| 1234 |
1.234 x 103 |
1.234E3 |
| 98765 |
9.8765 x 104 |
9.8765E4 |
| 0.0123 |
1.23 x 10-2 |
1.23E-2 |
| 0.000625 |
6.25 x 10-4 |
6.25E-4 |
- Letter
E stands for exponent
- Number following
E represents a power of 10
- Indicates the number of decimal places to move for standard decimal value
- A positive power of 10 moves the decimal point to the right
- A negative power of 10 moves the decimal point to the left
How Large is 1.7E308?
- Largest possible
double is 17 followed by 307 zeros
- How large is that?
- Current estimate of the number of atoms in the universe: about
1.0E78
- Mathematicians use the term "googol" for a very large number:
1.0E100
- Data type
double easily encompasses these numbers
- What value cannot be represented by type
double?
^ top
3.1.3: Arithmetic
- You can write code to perform arithmetic on integers and floating-point numbers
- Java uses special symbols to perform the operations:
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus (remainder)
- For example:
3 + 4
12 - 7
12.3 + 4.56
.065 * 1200
18 / 2
17.4 / 3.3
We can use these expressions to perform arithmetic and display the results
System.out.print(3 + 4); // prints 7
Unary Operators
- Operators
+, -, *, /, % are called binary operators
- Always need two operands (numbers) to work with one operator
- Java also provides a unary operator:
- (minus sign)
- Reverses the sign of a number
- Some examples:
-1 -5.3 - -1
Java also provides a plus sign (+) unary operator
Notes About Arithmetic Expressions
- Parenthesis can be used to group expressions
- Anything within parenthesis is evaluated first
2 * (10 + 5)
- You can have parenthesis within parenthesis
- Innermost parenthesis evaluated first
(2 * (10 + 5))
- Parenthesis cannot be used to indicate multiplication
- Invalid expression:
(2)(3)
- Must use the
* operator
- Two binary operators cannot be placed side by side
- Invalid expression:
5 * % 6
- Operators
* and % cannot be next to each other
Programming Style
- Programming style: add spaces around binary operators
- Programming style: no spacing after opening or before closing parenthesis
^ top
3.1.4: Operator Precedence
- Often need to process expressions of greater complexity than two numbers
- May need more than one operator
- Java has certain rules that must be followed
Precedence Rules
- Precedence: what gets done first
- Arithmetic operators are processed in algebraic order:
- Parenthesis:
( )
- Unary operators:
+, -
- Multiplication, division, modulus:
*, /, %
- Addition, subtraction:
+, -
- Binary operators of same precedence are evaluated from left to right
Examples of Expressions
| Algebra Expression |
Java Expression |
Fully Parenthesized |
| 2(10 + 5) |
2 * (10 + 5) |
(2 * (10 + 5)) |
1
12.2 + 3 · 7.3 |
1 / (12.2 + 3 * 7.3) |
(1 / (12.2 + (3 * 7.3))) |
10 - 7
3.2 + 9 · 1.6
|
(10 - 7) / (3.3 + 9 * 1.6) |
((10 - 7) / (3.3 +(9 * 1.6))) |
| 2 · 42 |
2 * 4 * 4 |
((2 * 4) * 4) |
- The fully parenthesized column shows the precedence explicitly
^ top
3.1.5: Mixed-Mode Expressions
- Recall that different data types are stored in different forms
- An
int is stored in 4 bytes
- A
double is stored in 8 bytes
- The format they are stored in is different as well
- Computer needs both operands in the same form before it can perform an operation
- If one operand is different than the other, the compiler converts it to a wider type
- For example:
2 + 3.3
First number (2) is an int
Second number (3.3) is a double
First number is narrowest (uses the fewest bytes), thus it gets promoted to a double (i.e. 2.0)
Then the arithmetic operation can take place to produce a result of 5.3
Remember that the result of arithmetic with an int and a double is a double
^ top
3.1.6: Integer Division and Modulus
- Dividing two integers can produce unexpected results for the unwary
- For example, what is the result of the following expression?
7 / 2
Since both numbers are of type int, one does not get a floating-point result
Remainder portion is truncated (discarded, thrown away)
Modulus Operator
- Sometimes you want to know the remainder of an integer division
- Java provides the modulus operator:
% (percent sign)
- Returns the remainder of the division of first number by the second
- For example:
7 % 2 // returns 1
7 % 2 returns 1 because 1 is the remainder when 7 is divided by 2
Check Yourself
What is the result of the following arithmetic operations?
- 9 / 4
- 17 / 3
- 14 / 2
- 9 % 4
- 17 % 3
- 14 % 2
^ top
3.1.7: Mathematical Methods
- Only the simplest mathematical operations are provided by operators
- For more complex operations, you use mathematical methods
System.out.println(Math.sqrt(9.0));
Java provides the Math class that contains many such methods
| Name |
Description |
Example |
Result |
| abs |
absolute value |
Math.abs(-3.9) Math.abs(3.9) |
3.9 3.9 |
| exp |
exponent |
Math.exp(1.0) |
2.718... |
| log |
natural log |
Math.log(10.0) |
3.20... |
| pow |
powers |
Math.pow(2.0, 3.0) |
8.0 |
| sqrt |
square root |
Math.sqrt(4.0) |
2.0 |
In addition, includes three similar methods: round, floor, and ceil
| Name |
Description |
Example |
Result |
| ceil |
ceiling: round up |
Math.ceil(3.3) Math.ceil(3.7) |
4.0 4.0 |
| floor |
floor: round down |
Math.floor(3.3) Math.floor(3.7) |
3.0 3.0 |
| round |
round: round off |
Math.round(3.3) Math.round(3.7) |
3.0 4.0 |
All three return whole numbers, although they are of type double
Using Mathematical Methods
- How are mathematical methods evaluated?
- Whatever is within the parenthesis of the method call is evaluated first
- Thus, in the following example, we get the square root of
9.0
System.out.println(Math.sqrt(3.0 * 3));
If the method is used in an arithmetic expression, they are handled just like a number of the type returned
For example, in the following, the value 4.0 is stored in the double variable num:
double num = 1 + Math.sqrt(3.0 * 3.0);
System.out.println(num);
Note that the method evaluates the sqrt(3.0 * 3) before adding it to 1.0
Thus methods have a higher precedence than arithmetic operators
^ top
3.1.8: Summary
- Java uses the following operators for arithmetic
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus (remainder)
- The dash (minus sign) is also used for negation
- Arithmetic expressions are combinations of numbers, variables, constants and operators
double area = 0.0, radius = 4.5;
final double PI = 3.14159623;
area = PI * radius * radius;
Operators have the same precedence as in algebra
- Parenthesis:
( )
- Method calls
- Unary operators:
+, -
- Multiplication, division, modulus:
*, /, %
- Addition, subtraction:
+, -
Results of integer division are truncated
Must use modulus operator (%) to get the remainder value
More complex mathematical operations are available using the Math class
System.out.println(Math.sqrt(3.0 * 3));
Check Yourself
- How can you tell the difference between a literal integer and a literal floating-point number?
- What is meant by the term: expression?
- What are the five operators Java provides for arithmetic?
- What type is returned from an expression when an
int and a double are added together?
- What is the result of the following arithmetic expressions?
7 / 3
7 % 3
- What is meant by the term precedence?
- How do you calculate the square root of a number like
27?
^ top
Exercise 3.1
- Start a text file named exercise3.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 3.1
- Complete the following specifications and record the answers to any questions in exercise3.txt.
Specifications
Through the miracles of computer science, we will now convert your $1000 computer into a $10 calculator!
- Copy the following program into a text editor and then save, compile and run the program.
1
2
3
4
5
|
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
|
- Replace the
"Hello, World!" portion of the program (line 3) with the arithmetic expression (7 + 2) and then recompile and run the program. Specifically, the line should read:
System.out.println(7 + 2);
Q1: What value was displayed by the computer?
- Use the expression
(7 / 2) and then recompile and run the program.
Q2: What value was displayed by the computer? Why?
- Change the expression to use
(7 % 2) and then recompile and run the program.
Q3: What value was displayed by the computer? Why?
- The following are algebraic expressions and an incorrect translation to code. Find the errors and write corrected code. Save the corrected expressions in
exercise3.txt.
| Algebraic Expression |
Incorrect Translation |
| (2)(3) + (4)(5) |
(2)(3) + (4)(5) |
6 + 18
2 |
6 + 18 / 2 |
|
|
5 / 9 * (100 - 32) |
| 2 · 42 |
2 * 4 ^ 2 |
^ top
3.2: Strings and Characters
Objectives
At the end of the lesson the student will be able to:
- Identify characters and strings from their literal representation
- Assign characters and strings to variables
- Concatenate strings
- Use methods of class
String
- Perform arithmetic on characters
|
^ top
3.2.1: Introduction to Strings
- Strings are objects in Java
- This means that strings can have methods as we shall see later
- Even though strings are objects, they have some special syntax to make their use easier
Literal Strings
- String literals are made by enclosing a sequence of characters in double quotes
- For example:
"abc" "b" "3.24159" "$3.95" "My name is Ed"
Double quotes used to mark the beginning and end of a string are not stored
Notice that the string "3.24159" could be expressed as a double by removing the quotes
However, a computer stores these two values very differently
double type 3.24159 is stored in eight bytes using the IEEE 754-1985 standard
String type "3.24159" is stored as Unicode characters
Both data types are useful for solving different problems
^ top
3.2.2: Declaring and Assigning Strings
- As with other data types, you must declare string variables before use
String message;
You can assign literal strings to String variables using the assignment operator
String message = "Hello Mom!";
System.out.println(message);
You can assign other String objects to a String object
String s1, s2;
s1 = "Hello Mom!";
s2 = s1;
System.out.println(s2);
^ top
3.2.3: Joining Strings
- You can join two
string objects together using the '+' operator
- The join operation is called concatenation
String s1 = "Hello", s2 = "Mom!";
String s3 = s1 + s2;
System.out.println(s3);
The string s3 now has the contents of both s1 and s2
You can also mix string variables and literal strings
string s1 = "Hello", s2 = "Mom!";
string s3 = s1 + " " + s2;
System.out.println(s3);
The double quotes around the space is a literal string
Now our output looks better
Mixed Joins
- You can output strings and other data types using
System.out.println() and the contatenation operator '+'
System.out.println("The number is: " + 3);
The number gets converted to a String and then concatenated with the rest of the string
Note that the + operator has the same precedence for strings and numbers
Can sometimes produce surprising results
For instance, what is output by the following?
int a = 1, b = 2;
System.out.println(a + b + "A");
System.out.println("A" + a + b);
^ top
3.2.4: String Methods
- Since strings are objects, you can call methods of class
String
- Syntax for calling a method of an object:
stringName.method(arguments)
You can look these methods up in the API documentation
String API: http://java.sun.com/j2se/1.5/docs/api/java/lang/String.html
Some of the more commonly used methods are listed below
Some Commonly-Used String Methods
- length(): Returns the length of the string
- charAt(int): Returns a char at the specified index.
- toLowerCase(): Returns a new string with all characters in lowercase.
- toUpperCase(): Returns a new string with all characters in uppercase.
For Example
1
2
3
4
5
6
7
8
9
10
|
public class StringMethods {
public static void main(String[] args) {
String example = "Hello Mom!";
System.out.println(example);
System.out.println(example.length());
System.out.println(example.charAt(0));
System.out.println(example.toLowerCase());
System.out.println(example.toUpperCase());
}
}
|
^ top
3.2.5: Type char
- A character is a letter, number or special symbol
- For example:
'a' 'b' 'Z' '3' 'q' '$' '*'
Java provides the char data type to represent characters
Characters are stored in the Unicode format
Unicode includes all ASCII codes plus additional codes for languages with an alphabet other than English
Declaring and Assigning char Variables
- As with other data types, you must declare
char variables before use
char letter;
You assign values to a char variable using the equals sign
letter = 'A';
Just like numbers, you can combine declaration and assignment into one statement
char letter = 'A';
Also, you can declare multiple variables one one line:
char letter, letterA = 'A', letterB = 'B';
In addition, you can declare char constant values
final char AND = '&';
^ top
3.2.6: char Arithmetic
- Type
char can be treated like an integer type
- This is because Unicode uses the same binary form as integers
- This allows the programmer to perform arithmetic on char values
- For example, you can add and subtract integer values to a
char variable
char letter = 'A' + 2;
System.out.println(letter); // displays 'C'
What is the value of letter after the following code executes?
char letter = 'c' - 'a' + 'A';
System.out.println(letter);
^ top
3.2.7: Summary
- You make string literals by enclosing characters in double quotes
"abc" "b" "3.24159" "$3.95" "My name is Ed"
You declare string variables using String as the data type
String s1 = "Hello Mom!";
To concatenate two strings, use the "+" operator
String s2 = s1 + " See yah!;
You use methods of the String object for some operations
String example = "Hello Mom!";
System.out.println(example.charAt(0));
A character is a letter, number or special symbol
You make character literals by enclosing a single character in single quotes
'a' 'b' 'Z' '3' 'q' '$' '*'
You declare character variables using char as the data type
char letter = 'A';
final char AND = '&';
Since char types are really integers, you can add and subtract them
char letter = 'A' + 2;
char letter2 = 'c' - 'a' + 'A'
Check Yourself
- What type of delimiters are used to encapsulate literal strings?
- What is the code to declare a string variable named
foo?
- What operator is used to join two strings?
- How do you determine the length of a string variable?
- How do you determine the first character stored in a string variable?
- What type of delimiters are used to encapsulate single characters?
- Why can you perform arithmetic with
char values?
^ top
Exercise 3.2
Strings are made up of characters. To explore how strings and charcters are related, complete the program following the specifications.
Specifications
- Use the starter code shown below to get started on this exercise.
- Save the code as:
HelloDown.java
- Write a program to display a five-character
message string down the page like this:
H
e
l
l
o
- Use the
charAt() method to extract each character from message. Do NOT simply print each letter.
- Submit your source code file as the answer to this exercise. Do NOT copy your code into
exercise3.txt.
1
2
3
4
5
6
7
|
public class HelloDown {
public static void main(String[] args) {
String message = "Hello";
// Enter code here
}
}
|
^ top
3.3: Libraries and Console I/O
Objectives
At the end of the lesson the student will be able to:
- Import standard API classes
- Create objects and call methods
- Display information to a console
- Get user input from the console
|
^ top
3.3.1: Importing Classes
- To make it easier to write programs, Java has many libraries
- These libraries contain prewritten code
- Referred to as the Java Application Programming Interface (API)
- Recall that all Java code is stored in classes
- Groups of related classes are organized into packages
Some Commonly Used Packages
| Package Name |
Description |
java.lang |
Provides classes fundamental to Java. |
java.io |
Provides classes to read and write files. |
java.txt |
Provides classes to handle text, dates, and numbers |
java.util |
Provides classes to work with collections and miscellaneous utilities. |
javax.swing |
Provides classes to create graphical user interfaces and applets. |
Importing Classes and Packages
- Classes in the
java.lang package are available automatically
- To use other classes, you must import them
import packagename.ClassName;
or
import packagename.*;
Using the '*' wildcard will import all classes in a package
For example:
import java.text.NumberFormat;
import java.util.Scanner;
import java.util.*;
import javax.swing.*;
Navigating the API
- The Java API is located at: http://java.sun.com/j2se/1.5/docs/api/index.html
- Related classes are organized into packages
- Shown in the upper left frame
- When you select a package, all the classes for that package are shown in the lower left frame
- Once you select a class, it is shown in the right frame
- Each class shows a variety of information including a summary of all its methods
- To view the information about a method, either click on its hyperlink or scroll down the page
^ top
3.3.2: Creating Objects and Calling Methods
- To use a Java class, you usually start by creating an object of the class
- Also known as creating an instance of the class
- There are two steps to creating an object:
- Create a variable to store the object
- Create the object using the
new operator and assign it to the variable
- To create the variable, you code the class name followed by an identifier
- For example:
Scanner input;
To create the object, you use the new operator followed by the class name to assign a value to the variable
input = new Scanner(System.in);
When you create the object, you often pass it an argument like System.in as shown
The arguments are specified by the constructor as shown in the API documentation
You can combine both steps into one statement, like:
Scanner input = new Scanner(System.in);
When we cover objects in a few weeks, we will discuss this in more detail
Calling Object Methods
- One you create an object, you can call its methods
- Note that some classes have static methods that you can call without creating an object
- To call a method, you use the object name, a dot (period), the method name and a set of parenthesis
- For example:
input.nextInt();
When you call a method, the method may require one or more arguments
These arguments must be coded in the correct sequence separated by commas
System.out.println("Hello, World!");
^ top
3.3.3: Printing to a Console
- Two useful prewritten methods are
print() and println()
- Their purpose is to display data
- The difference between the two methods is that:
print() leaves the cursor positioned after the last character
println() positions the cursor on a new line
- Cursor position determines where the next character is displayed
System.out.print("Hello, ");
System.out.println("world!");
In this statement, out is the name of an object in a Java class named System
System is automatically created whenever a Java program is executed
System.out lets a program know to send data to the standard output stream
- Usually the video display screen
The data to display is passed to the method within the parenthesis
Escape Sequences
- Some characters are more difficult to code output for than others
- For example, what would the compiler do with the following statement?
System.out.println("Say, "Hey!"");
Some characters cannot be output directly in a string
Also, the first 32 ASCII characters are not visible on our monitors
- Known as control codes because they control the output device
Even though these characters are not visible, we sometimes need to use them
- For example, a newline character
We need some way to "print" invisible and hard-to-print characters
Java can access some of the control codes and hard-to-print characters using escape sequences
Backslash (\) directly in front of a certain character tells the compiler to escape from the normal interpretation
Following table has some nonprinting and hard-to-print characters:
| Sequence |
Meaning |
Unicode Value |
|
Alert |
\u0007 |
\b |
Backspace |
\u0008 |
\f |
Formfeed |
\u000C |
\n |
Newline |
\u000A |
\r |
Carriage return |
\u000D |
\t |
Horizontal tab |
\u0009 |
\\ |
Backslash |
\u005C |
\" |
Double quote |
\u0022 |
\' |
Single quote |
\u0027 |
Some examples:
System.out.print('\u0007');
System.out.print('\n');
System.out.print("Left\tRight");
System.out.print("one\ntwo\nthree");
Programming Style
^ top
3.3.4: Reading Input from the Console
- You can read input from the command line (console) using a
Scanner object
- Located in the
java.util package, so you need to import the class
import java.util.Scanner;
or
import java.util.*;
You then create a scanner class like:
Scanner input = new Scanner(System.in);
Note that System.in is used to get data from the standard input stream
To use one of the methods of a Scanner object, call it like the following:
int count = input.nextInt();
When you call a method of a Scanner object, the program waits for the user to enter data with the keyboard
Each group of characters that a user enters is called a token
The program waits until the user presses the Enter key
The user can enter multiple tokens by separating them with whitespace
If the user enters the wrong type, an error occurs and the program aborts
When you combine different scanner methods, you sometimes have to include an extra call to nextLine() to get rid of a newline
Some Commonly Used Methods of a Scanner Object
- Here are some commonly used methods of a Scanner object
| Method |
Description |
next() |
Returns the next token as a String object. |
nextLine() |
Returns the rest of the current line as a String object. |
nextDouble() |
Returns the next token as an double value. |
nextInt() |
Returns the next token as an int value. |
For Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.util.Scanner;
public class InputApp {
public static void main(String[] args) {
String name;
int age;
double weight;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
name = input.next();
System.out.print("Enter your age: ");
age = input.nextInt();
System.out.print("Enter your weight: ");
weight = input.nextDouble();
System.out.println("\nYou entered:");
System.out.println("Name:" + name);
System.out.println("Age:" + age);
System.out.println("Weight:" + weight);
}
}
|
Scanner Pitfall: next() vs. nextLine()
- Notice the difference between methods
next() and nextLine()
- Method
next() first skips whitespace and reads until it finds whitespace again
- Method
nextLine() reads the remainder of a line of text, starting wherever the last read left off, but excluding the '\n' at the end of the line
- Thus, you use
nextLine() if you allow spaces in the input
System.out.print("Enter your name: ");
name = input.nextLine();
User Input with Type char
- Note that you cannot input type
char directly using Scanner
- Instead, you can input a
String and select a char using the charAt() method
- For example, to read the first character of an input string:
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String entry = input.next()
char letter = entry.charAt(0);
System.out.println("You entered: " + letter);
^ top
3.3.5: Summary
- To make it easier to write programs, Java has many libraries of prewritten code
- You can make use of this code by importing packages
import packagename.ClassName;
or
import packagename.*;
For example, to import all the java.util libraries
import java.util.*;
Alternatively, you can use the fully qualified package name
import java.util.Scanner;
To create an object for a class, you:
- Create a variable to store the object
- Create the object using the new operator and assign it to the variable
You can combine both steps into one statement, like:
Scanner input = new Scanner(System.in);
One you create an object, you can call its methods
To call a method, you use the object name, a dot (period), the method name and a set of parenthesis
For example:
input.nextInt();
You can use the System.out object to print to the console
System.out.print() leaves the cursor positioned after the last character
System.out.println() positions the cursor on a new line
You can use a Scanner object to read data from the console
To use Scanner, you need to need to import the java.util.Scanner class
You then create a Scanner object like:
Scanner input = new Scanner(System.in);
Each group of characters that a user enters is called a token
To read each token, you call a method of a Scanner object
int count = input.nextInt();
Check Yourself
- How do you include libraries in your Java programs?
- What does the acronym "API" stand for? What does it mean?
- How do you create an object?
- How do you call a method of an object?
- What is the escape sequence for a newline?
- What library do you include to create
Scanner objects?
- What is the code to create a
Scanner object?
- What is the code to get an
int value from the keyboard using a Scanner object?
^ top
Exercise 3.3
Complete the program following the specifications.
Specifications
- Write a program to read an
int from the keyboard and display it to the console.
- Save the code as:
ReadAndDisplayInt.java
- Submit your source code file as the answer to this exercise. Do NOT copy your code into
exercise3.txt.
1
2
3
4
5
6
7
8
9
10
11
12
|
import java.util.*;
public class ReadAndDisplayInt {
public static void main(String[] args) {
double num;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
// Enter your code here
}
}
|
^ top
3.4: Problem Solving and Pair Programming
Objectives
At the end of the lesson the student will be able to:
- Describe the steps for writing a program
- Discuss the pros and cons of pair programming
|
^ top
3.4.1: Solving the Problem
- Recall that programming is about solving problems using a computer program
- When you first start computer programming, you may think that the hard part is translating your ideas into code
- This is definitely not the case
- The most difficult part is finding a solution to the problem
- After finding a solution, translating your solution to code is a routine, almost mechanical, task
Problem Solving Phase (Review)
- Problem definition
- First step is to analyze and understand the problem
- We will look at this step in more detail in the next section
- Algorithm design
- Next step is to define an algorithm
- Set of steps that a computer can use to perform a task
- We will look at this step in more detail as well
- Algorithm (desktop) testing
- After developing an algorithm, you need to verify it is correct
- Develop a sample problem
- Walk through each step mentally or manually
- If there is an error, change the algorithm
^ top
3.4.2: Writing the Program
- After you are sure the algorithm works, then write the program code
- If your algorithm is correct, this phase is usually easy
Implementation Phase
- Translate the algorithm to Java code
- Start with a simple program that you know works (see template below)
- Add your algorithm to the code one step at a time
- Compile and run you program after you add each step
- If you find an error, correct it before continuing
- Computer testing
- After code compiles and runs, you test it
- When you test, make sure the program:
- Does what it is supposed to do
- Does not do what it is not supposed to do
- Does what it used to do
- Working program
- When it works well, you document and deliver the program
Starting Template
import java.util.*;
public class Template {
public static void main(String[] args) {
// Enter code here
}
}
^ top
3.4.3: Pair Programming
- Defining problems and developing algorithms on your own is often difficult
- Also, when you translate the algorithm into code, you often run into syntax errors that are difficult to see
- It would be nice to get help from another human in these cases
- However, the instructor prohibits asking most people from looking at your code
- What is the solution to this problem?
- Answer: Pair Programming for Homework Assignments
Defining Pair Programming
- Pair programming is two people work together on one computer at the same time
- Exactly two people: not one nor three or more
- Exactly one computer: not two or more
- The driver operates the keyboard and mouse
- The navigator actively participates in the programming
- Analyzes the design and code to prevent errors
- Also in charge of using printed reference materials like textbooks
- Each person "drives" about half the time
- Physically get up and move positions when switching roles
- At most 25% of your time is spent working alone
- Any work done alone is reviewed by the other person
- The objective is to work together and to learn from each other
- You cannot divide the work into two pieces with each partner working on a separate piece
Why Pair Program?
- Students who pair program report:
- Higher confidence in a program solution
- More satisfaction with programming
- Instructors report higher retention rates
More Information
^ top
3.4.4: Best Practices
- You may choose any other student in this class for a partner
- Both of your names appear on the assignment
- When choosing partners and working together, certain practices help you perform better
- Pair-programmers are more successful when they have similar experience levels
- Need to find a partner with whom you can exchange ideas easily
Getting Along
More Information
^ top
3.4.5: Summary
- Programming is about solving problems using a computer program
- To develop a computer program, you start by defining the problem(s) to solve
- Once a problem is well defined, you develop an algorithm to solve it
- Once the algorithm is define, then you write the program
- After the program compiles and runs, you test it to verify it works correctly
- Once the program works, you finish documenting it and then submit the code
- Since defining problems, developing algorithms and implementing algorithms is hard, you can work with a partner
- Use some care when choosing a pair-programming partner to maximize your success
- In addition, both you and your partner should read: All I Really Need to Know about Pair Programming I Learned In Kindergarten
Check Yourself
- Why is pair programming helpful?
- What are the rules of pair programming?
^ top
Exercise 3.4
- Label this exercise: Exercise 3.4
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in your exercise3.txt file.
Specifications
- We will count off and divide into separate groups
- Within your group, exchange email addresses so that you can send the answer to this exercise to each other.
- As a group, define the problem and describe an algorithm for converting weight measurements from pounds to grams.
- Describe the algorithm using pseudocode in your
exercise3.txt file.
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Schedule
| Expectations
| Course info
Help
| FAQ's
| HowTo's
| Links
Last Updated: October 09 2005 @21:03:01
|