summer 2008 q1version 1.21 introduction to programming session 2 point park university cmps 322...

36
Summer 2008 Q1 Summer 2008 Q1 Version 1.2 Version 1.2 1 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Upload: phyllis-hensley

Post on 19-Jan-2016

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1Summer 2008 Q1 Version 1.2Version 1.2 11

Introduction to ProgrammingSession 2

Point Park University

CMPS 322Summer 2008 Q1

Page 2: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 2

Questions

Questions and issues for last week's topics. Any issues with Netbeans?

Page 3: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 3

Java Data Types

Text reference begins at Page 34. Java variables fall into two categories:

– Intrinsic data types. byte, short, int, long char double, float boolean

– Intrinsic types are declared in this manner:

int myvar1;double total = 0.0;

int myvar1;double total = 0.0;

Page 4: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 4

Java Data Types

The second category of Java variables are known as reference variables.

The data types of reference variables a Java classes. Variables to store string data are reference variables. When we declare them, they actually aren’t ready to use yet. We must initialize them by tying them to an instance of the class.

String myname; // This is an unintialized variable.myname = new String(“Fred Flintstone”);

String yourname = new String(); // An empty string.

String myname; // This is an unintialized variable.myname = new String(“Fred Flintstone”);

String yourname = new String(); // An empty string.

Page 5: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 5

Declaring Variables

Your programs will need to be able to store data in them for computation and processing.

This will necessitate that you declare variables. Variables are storage locations in memory that you can refer to by a

name that has meaning to you for the context of the application. Variables are declared by selecting data type and variable name:

int myintvalue, j, k3;double salary = 10000.0;

int myintvalue, j, k3;double salary = 10000.0;

Note initialization syntax.

Note initialization syntax.

Page 6: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 6

Declaring Variables

Variables are not initialized automatically. Use of a variable before initialization is illegal in Java. May be initialized at time of declaration, or via assignment statement.

double salary = 10000.0;

salary = 22000.0;

double salary = 10000.0;

salary = 22000.0;

Page 7: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 7

Java Variable Names

Variable names or identifiers:– Can contain letters, digits, underscores and dollar signs.

– Must start with letter, underscore or dollar sign. (Not a digit.)

– Cannot be a reserved word. See Appendix A of text for list of reserved words.

– Cannot be true, false or null.

– Have no limit to length.

int myvar1;double total = 0.0;String _StudentNameValue;int ___placemarker;

int myvar1;double total = 0.0;String _StudentNameValue;int ___placemarker;

Page 8: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 8

Arithmetic Expressions

Most programs will need to support numeric calculations. This is accomplished via statements that combine variables with the

arithmetic operators.– +, -, *, /, %.

These operators are the binary operators.– They require left and right operands.

There are also a number of unary operators, notably:– ++, --, +=, -=, *=, /=.

The complete set of Java operators, and their precedence, is shown on Page 86.

Page 9: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 9

Type Casting

Type casting involves stating what your target data type is. Syntax is to place target data type within parentheses, in front of data

to be converted.

int j;j = (int) 3.24;

int j;j = (int) 3.24;

Page 10: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 10

Formatting Numbers

Unless you request it, numeric output is raw and often ugly. Formatting numbers in Java is not hard, but it is not intuitive. Must make use of the NumberFormat object. We create a variable that acts as the formatting tool. When we want to display the number formatted, as ask the tool to do

its job.

NumberFormat numberformat = NumberFormat.getInstance(Locale.US);System.out.print(numberformat.format(dblFarenheit));

NumberFormat numberformat = NumberFormat.getInstance(Locale.US);System.out.print(numberformat.format(dblFarenheit));

Page 11: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 11

Formatting Numbers

Must import the java.util.NumberFormat package, or java.util.*. There are different types of formatting instances available to you.

– Each customized to different types of numbers.

NumberFormat also supports several methods to control such things as number of decimal places.

See the Java Online documentation for full information. See the solutions to last weeks in-class work on Blackboard.

form = NumberFormat.getInstance();form = NumberFormat.getIntegerInstance();form = NumberFormat.getCurrencyInstance();form = NumberFormat.getPercentInstance();

form = NumberFormat.getInstance();form = NumberFormat.getIntegerInstance();form = NumberFormat.getCurrencyInstance();form = NumberFormat.getPercentInstance();

form.setMaximumFractionDigits(2);form.setMinimumFractionDigits(2);

form.setMaximumFractionDigits(2);form.setMinimumFractionDigits(2);

Page 12: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 12

Getting User Input

Unfortunately, not as easy as it should be in Java. Two choices:

– Use a Scanner object (newer technique).

– Use an InputStream object (older technique).

Scanner somewhat easier, but can be cranky. InputStream bulletproof, but harder to use. I have provided two examples of code using each technique.

Page 13: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 13

Input Via Scanner

Must import the java.util.Scanner package, or java.util.*. See Section 2.13 of text for discussion on use. To actually get input, must use of the “next” methods.

– Text does not list nextLine(), but it is another string input method.

Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer value: ");int intval = scanner.nextInt();

Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer value: ");int intval = scanner.nextInt();

Page 14: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 14

Scanner Secret!

next() method only gets first chunk of a string if it has spaces.– Must use nextLine() if you want a whole line of input that includes spaces.

– But nextLine() will be fooled by any previous input of numeric values. This is because nextInt(), nextDouble() leave the enter key character(s) in the

keyboard buffer.

– To successfully use the Scanner to get strings from the keyboard, clear it before asking for input.

But only if you have previous input.

Scanner scanner = new Scanner(System.in); scanner.nextLine(); // This clears things out first.System.out.print("Enter your full name: ");String fullname = scanner.nextLine();

Scanner scanner = new Scanner(System.in); scanner.nextLine(); // This clears things out first.System.out.print("Enter your full name: ");String fullname = scanner.nextLine();

Page 15: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 15

The Input Stream Approach

This is the original way that Java console input was conducted. Requires several things to be done with your code to get it set up

properly. Step 1: Indicate that your main() method throws and IOException.

public static void main(String args[]) throws IOException

public static void main(String args[]) throws IOException

Page 16: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 16

The Input Stream Approach

Step 2: Create a BufferedReader object.

// Set up input channel.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

// Set up input channel.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Page 17: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 17

The Input Stream Approach

Step 3: Read in a line of input.– Note: All input that comes in is a character string.

String input;

System.out.print("Enter adjusted gross income: ");input = in.readLine();

String input;

System.out.print("Enter adjusted gross income: ");input = in.readLine();

Page 18: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 18

The Input Stream Approach

Step 4: Converting to your target data type.– Note: All intrinsic data types have a partner reference type (class) that

supports parsing of values from a string.

– This is very similar to what you did in HTML class with JavaScript.

income = Double.parseDouble(input);income = Double.parseDouble(input);

Page 19: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 19

The Input Stream Approach

Putting it all together (complete code on Blackboard).

public static void main(String args[]) throws IOException{ // Set up input channel. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

// Declare support variables. double income,taxdue; String input;

System.out.print("Enter adjusted gross income: "); input = in.readLine(); income = Double.parseDouble(input);

public static void main(String args[]) throws IOException{ // Set up input channel. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

// Declare support variables. double income,taxdue; String input;

System.out.print("Enter adjusted gross income: "); input = in.readLine(); income = Double.parseDouble(input);

Page 20: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 20

If Statements

First, let’s look at the available relational operators:– == Equal to

– != Not equal to

– < Less than

– > Greater than

– <= Less than or equal

– >= Greater than or equal

These are complemented by the compound operators:– && And

– || Or

Defined on Page 68.

Page 21: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 21

If Statements

Refer to Chapter 3 in text. Used to code decision making statements in programs. Result of an if test is true or false. Syntax requires use of parentheses.

if (g > 2) ;g = 14

if (g > 2) g = 14;

Page 22: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 22

If Statements

General syntax:

if (){{else if(){{else{{

if (){{else if(){{else{{

Page 23: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 23

If Blocks

When more than one statement is to be executed (if the logical test is true), braces are used to form a block:

if (a >= b){

a = 3*b; i = i + 1;

{

if (a >= b){

a = 3*b; i = i + 1;

{

Page 24: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 24

The Else Clause

Many times it is necessary to take actions both when a condition is true or if it is false.

The else clause allows expansion of the if to accommodate this situation.

Page 25: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 25

Else Clause

When more than one statement is to be executed (if the logical test is true), braces are used to form a block:

if (a < b + 10){

System.out.println(“Curing too rapidly.”);{else{

iter = iter + 1;{

if (a < b + 10){

System.out.println(“Curing too rapidly.”);{else{

iter = iter + 1;{

Page 26: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 26

The Else If Extension

Multiple tests can be constructed through use of else if.

if (g + 1 != a*b) g = g + 1;

else if (a < 10) g = 2*g;

else if (a*b > 350) g = g*g;

else g = 0;

if (g + 1 != a*b) g = g + 1;

else if (a < 10) g = 2*g;

else if (a*b > 350) g = g*g;

else g = 0;

Page 27: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 27

Nested If Statements

If statements can be placed within other if statements.

if (g + 1 != a*b){ g = g + 1; if (a < 10) g = 2*g; else if (a*b > 350) g = g*g; else g = 0;{

if (g + 1 != a*b){ g = g + 1; if (a < 10) g = 2*g; else if (a*b > 350) g = g*g; else g = 0;{

Page 28: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 28

Nested If Statements

Be wary of how you structure nested ifs. An else always belongs to the nearest preceding if that’s not already

associated with another else. What does following code do?

int g = 3;int a = 0;if (g != 3) if (a < 10) System.out.println(“a < 10”);else System.out.println(“a not < 10”);

int g = 3;int a = 0;if (g != 3) if (a < 10) System.out.println(“a < 10”);else System.out.println(“a not < 10”);

Page 29: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 29

Compound IF Statements

Simple relational expressions can be joined into more complex expressions via the compound operators. && Logical AND || Logical OR

These operators have a precedence.And before or.

if (a < 10 && b == 3)System.out.printf(“%d %d\n”,a,b);

if (a < 10 && b == 3)System.out.printf(“%d %d\n”,a,b);

Page 30: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 30

Switch Statements

Switch statements are like if statements in many ways.– They clean up the syntax a little bit.

Similar to case statements of other languages. Means to compare an integer value against a list of cases. Refer to Page 81 of text. The break statement needed to prevent fall through execution.

Page 31: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 31

Switch Statements

General syntax:

switch (expression){ caseconstant1: statement sequence caseconstant2: statement sequence . . defaultstatement sequence :{

switch (expression){ case constant1: statement sequence case constant2: statement sequence . . default: statement sequence{

Page 32: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 32

Switch Statements

Specific example:

switch (a){ case 1 : System.out.println(“a = 1”); break; case 2 : System.out.println(“a = 2”); break; default : System.out.println(“a is not 1 or 2”);{

switch (a){ case 1 : System.out.println(“a = 1”); break; case 2 : System.out.println(“a = 2”); break; default : System.out.println(“a is not 1 or 2”);{

Page 33: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 33

Formatting Output

This is alternative to using NumberFormat object. The printf statement together with formatting codes can achieve a

limited degree of output formatting. See Tables 3.8 and 3.9 for available codes.

System.out.printf(“The value is %d dollars”,dblDollar);

System.out.printf(“The value is %10.2f dollars”, dblDollar);

System.out.printf(“%25s\n”,”Bob”);

System.out.printf(“The value is %d dollars”,dblDollar);

System.out.printf(“The value is %10.2f dollars”, dblDollar);

System.out.printf(“%25s\n”,”Bob”);

Page 34: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 34

Coding Sessions

Group work #1:– Write a program that reads a grade of A, B, C, D or F and then prints

“excellent”, “good”, “fair”, “poor” or “failure”.

– Use the if – else structure.

Group work #2:– Revise the above program to use a switch structure.

Page 35: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 35

Coding Sessions

Practice work:– Write a program that reads a user’s age and then prints:

“You are a child” if the age is less than 18. “You are an adult” if the age is greater than or equal to 18 and less than 65. “You are a senior citizen” if the age is greater than or equal to 65.

Page 36: Summer 2008 Q1Version 1.21 Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1

Summer 2008 Q1 Version 1.2 36

Assignments

Reading: Chapters 3 and 4 from text. Assignment 2.

– Due next week. Assignment 1 due today. Participate in discussion forums.