chapter 3 java basics

73
Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 3 Java Basics Introduction Primitive Types Constants Input Conversion between Types Ethics in Computing

Upload: irish

Post on 19-Jan-2016

35 views

Category:

Documents


2 download

DESCRIPTION

Chapter 3 Java Basics. Introduction Primitive Types Constants Input Conversion between Types Ethics in Computing. Introduction: Skeleton Programs. Skeleton Program for turtle graphics program // Comment that describes the program import turtlegraphics.*; public class className { - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 3 Java Basics

Programming and Problem SolvingWith Java

Copyright 1999, James M. Slack

Chapter 3Java BasicsIntroductionPrimitive TypesConstantsInputConversion between TypesEthics in Computing

Page 2: Chapter 3 Java Basics

Programming and Problem Solving With Java 2

Introduction: Skeleton ProgramsSkeleton Program for turtle graphics program

// Comment that describes the program

import turtlegraphics.*;

public class className{ public static void main(String[] args) throws TurtleException { // Put your Java statements here }}

Page 3: Chapter 3 Java Basics

Programming and Problem Solving With Java 3

Introduction: Skeleton ProgramsSkeleton Program for non-turtle graphics program

// Comment that describes the program

public class className{ public static void main(String[] args) { // Put your Java statements here }}

Page 4: Chapter 3 Java Basics

Programming and Problem Solving With Java 4

Introduction: KeywordsKeyword is reserved -- can’t use for identifier namesKeywords in Java

abstract boolean break byte byvalue*

case cast* catch char class

const* continue default do double

else extends false final finally

float for future* generic* goto*

if implements import inner* instanceof

int interface long native new

null operator* outer* package private

protected public rest* return short

static super switch synchronized this

throw throws transient true try

var* void volatile while

*Reserved but not used in Java version 1.1.

Page 5: Chapter 3 Java Basics

Programming and Problem Solving With Java 5

Introduction: Identifier NamesProgrammer must make up names for new classes,

methods, variablesRules for forming identifier names

Must start with letter, underscore (_), or dollar sign ($)Other characters must be letters, digits, underscores, or

dollar signsNo spaces!No keywords

Page 6: Chapter 3 Java Basics

Programming and Problem Solving With Java 6

Introduction: Identifier NamesIdentifiers should also be meaningful to human readersPart of good programming style

Unacceptable to thecompiler

Acceptable to the compiler

Poor Style Good Style

Person Class p3 PersonClass

Person-Class PC Person_Class

**WELCOMEMESSAGE** WELCOMEMESSAGE WELCOME_MESSAGE

class Class AlgebraCourse

12MoreDrawings D12T Draw12Triangles

Page 7: Chapter 3 Java Basics

Programming and Problem Solving With Java 7

Introduction: Identifier NamesMany identifiers use more than one wordExamples: SmartTurtle, turnRightJava conventions

After the first word, begin each word with a capital letterClass names start with capital letter (SmartTurtle)Other names start with lower-case letter (turnRight)

Page 8: Chapter 3 Java Basics

Programming and Problem Solving With Java 8

Introduction: The main() MethodThe main() method is the one that starts with

public static void main(String[] args) …

Write executable instructions between bracesExecutable instruction: makes computer do somethingExamples of executable instructions

System.out.println("Hello!");myTurtle.turnRight(90);

Examples of non-executable instructionspublic static void main(String[] args)import turtlegraphics.*;

Computer starts executing the first statement in main()

Page 9: Chapter 3 Java Basics

Programming and Problem Solving With Java 9

Introduction: Flow of ControlWrite executable statements like a list

Write first instruction you want the computer to doThen write second, and so on

Sequential executionComputer executes each instruction in turn, in order they

appear in programComputer stops after executing last instruction

"Control"When computer executing instruction, control is at that

instruction

Page 10: Chapter 3 Java Basics

Programming and Problem Solving With Java 10

Introduction: SemicolonsSemicolon required after each executable

instructionmyTurtle.move(100);myTurtle.turnRight(90);

Free-form inputCompiler ignores indentation, ends of lines (as long as

words & other tokens not split)Example of valid program

// (This program has poor formatting)import turtlegraphics.*; public class DrawSimpleDesign { public static void main(String[] arguments) throws TurtleException { Turtle myTurtle = new Turtle(); myTurtle.move(400); myTurtle.turnRight(90); myTurtle.move(200); } }

Page 11: Chapter 3 Java Basics

Programming and Problem Solving With Java 11

Introduction: Letter CaseJava is case-sensitiveCompiler treats upper and lower case letters

differentlyA different from aB different from bpublic static void different from PUBLIC STATIC VOID

Some languages (Pascal) are case-insensitive

Page 12: Chapter 3 Java Basics

Programming and Problem Solving With Java 12

Introduction: CommentsComment starts with // and continues to end of line

// This program draws a squaremyTurtle.move(100); // Position turtle for next figure

Compiler ignores commentsProgrammer should include comments

Describe what the program doesDescribe (in higher-level terms than the code) how the

program worksUsually unnecessary to comment each line --

makes program too wordymyTurtle.move(100); // Move 100 unitsmyTurtle.turnRight(90); // Turn 90 degrees

Page 13: Chapter 3 Java Basics

Programming and Problem Solving With Java 13

Introduction: StreamsStream

A sequence of charactersHas a reader (consumer of information)

at one endHas a writer (producer of information) at

the otherProgram's input and output are streams

Output stream is the textual output of the program Input stream is the textual input of the program

ReaderWriter Stream

Page 14: Chapter 3 Java Basics

Programming and Problem Solving With Java 14

Introduction: System.out StreamSystem.out is the standard Java output stream

System is the name of a standard Java classout is the output stream object in the System classRefer to this output stream as System.out

Allows displaying text output on the consoleSystem.out.println("Hello!");

println() is method of out streamSyntax for method use

object.method(arguments);

Action of println()Display message on console

at cursor's position

Hello!

Page 15: Chapter 3 Java Basics

Programming and Problem Solving With Java 15

Introduction: println() vs. print()System.out.println()

Displays message, then moves cursor to beginning of next line

System.out.println("First message");System.out.println("Second message");

First messageSecond message_

System.out.print() Just displays message (leaves cursor after)

System.out.print("First message");System.out.print("Second message");

First messageSecond message_

Cursor

Cursor

Page 16: Chapter 3 Java Basics

Programming and Problem Solving With Java 16

Introduction: Use of print()Use System.out.print() to display several values on

same line// Displays the message, because there's a println()// after the print().

public class DisplayMessage{ public static void main(String[] args) { System.out.print("This"); System.out.print(" will"); System.out.println(" display"); }}

Page 17: Chapter 3 Java Basics

Programming and Problem Solving With Java 17

Hello

Introduction: Use of flush()Message from System.out.print doesn't display right

away -- stored in bufferUse System.out.flush() to force display of output

from System.out.print()

Hello!

Buffer

System.out.print("Hello!");

System.out.flush();

Page 18: Chapter 3 Java Basics

Programming and Problem Solving With Java 18

Introduction: The Output BufferOutput goes to the output buffer before the screenSystem.out.println("Here is");System.out.print("a small");System.out.print(" test");System.out.flush();

Buffer

Here is

Here is_

a smalla small test

Here isa small test_

Page 19: Chapter 3 Java Basics

Programming and Problem Solving With Java 19

Displaying String LiteralsDisplay string literals between quotes

System.out.println("This is a string literal");

Three ways display a long string literalLet the literal go past the edge of the editor screen

System.out.println("This is a very very very very very ver

Break the string into two strings, use print() on first, println() on second

System.out.print("This is a very very very very very ");System.out.println("very very very long message");

Use concatenationSystem.out.println("This is a very very very very very " + "very very very long message");

Page 20: Chapter 3 Java Basics

Programming and Problem Solving With Java 20

Introduction: Escape SequencesCan't display double quote " directly

This statement doesn't compileSystem.out.println("She said, "Hi!"");

Compiler can't find end of the stringUse escape character \ before " in string

System.out.println("She said, \"Hi!\"");

Other escape sequences\b Backspace\\ Backslash\a Bell\n End of line\t Tab

Page 21: Chapter 3 Java Basics

Programming and Problem Solving With Java 21

Primitive TypesType is a kind of informationMust define the type of information in a programThree common types of information

TextualNumericMultimedia

Two kinds of numeric types Integer: whole numbers (4, 99, -123)Floating point (4.35, -33.4, 3.0)

Page 22: Chapter 3 Java Basics

Programming and Problem Solving With Java 22

Primitive Type: Integers

Display integerSystem.out.println(123);

Display result of integer arithmeticSystem.out.println(123 + 456);

Display a message with an integerSystem.out.println("The answer is " + 123);

Display a message with integer arithmetic (wrong)System.out.println("The sum is " + 123 + 456);

Compiler treats + as concatenation!Display a message with integer arithmetic (correct)

System.out.println("The sum is " + (123 + 456));

123579The answer is 123The sum is 123456The sum is 579

Page 23: Chapter 3 Java Basics

Programming and Problem Solving With Java 23

Primitive Types: Integer Operators

Operation Symbol Example Result

Addition + 26 + 10 36

Subtraction - 26 - 1 25

Multiplication * 26 * 10 260

Division / 26 / 10 2

Modulus(remainder)

% 26 % 10 6

Page 24: Chapter 3 Java Basics

Programming and Problem Solving With Java 24

Primitive Types: Integer OperatorsOperator precedence: order of execution of

operatorsExample

System.out.println(30 + 10 / 2);

Possible interpretations3010

220

and

3010

235

Precedence Level Operation

High ()

Medium *, /, %

Low +, -

correct!

Page 25: Chapter 3 Java Basics

Programming and Problem Solving With Java 25

Primitive Types: Integer OperatorsEvaluation of some sample expressions

Expression How Java Evaluates Result

30 + 10 / 2 30 + (10 / 2) 35

25 + 16 - 10 (25 + 16) - 10 31

80 - 60 + 10 (80 - 60) + 10 30

50 - 10 * 3 50 - (10 * 3) 20

70 / 10 * 3 (70 / 10) * 3 21

15 * 2 / 3 (15 * 2) / 3 10

Page 26: Chapter 3 Java Basics

Programming and Problem Solving With Java 26

Primitive Types: Integer Types

IntegerType Size Smallest Value Largest Value

byte 1 byte(8 bits)

127 128

short 2 bytes(16 bits)

32,768 32,767

int 4 bytes(32 bits)

2,147,483,648 2,147,483,647

long 8 bytes(64 bits)

9,223,372,036,854,775,808 9,223,372,036,854,775,807

Page 27: Chapter 3 Java Basics

Programming and Problem Solving With Java 27

Primitive Types: Floating PointFloating-point number has

Decimal point, orExponent, or both

Examples5.0, 12.34, 0.0, -45.8, 12.

Scientific notation5.6 x 1027

= 5,600,000,000,000,000,000,000,000,000.0In Java

5.6E27

Page 28: Chapter 3 Java Basics

Programming and Problem Solving With Java 28

Primitive Types: Floating PointDisplay floating point number

System.out.println(18.7856);

Display a message, tooSystem.out.println("F.P. # is " + 18.7856);

Display a large floating point numberSystem.out.println("F.P. # is " + 123456789.0);

Large number display rule If more than 6 digits

display in scientific notationElse display in conventional notation

18.7856F.P. # is 18.7856F.P. # is 1.23457e008

Page 29: Chapter 3 Java Basics

Programming and Problem Solving With Java 29

Java Statement Display

System.out.println(0.000123456); 0.000123456

System.out.println(0.0001234567); 0.000123457

System.out.println(0.12345); 0.12345

System.out.println(0.123456); 0.123456

System.out.println(0.1234567); 0.123457

System.out.println(123.45); 123.45

System.out.println(1234.56); 1234.56

System.out.println(12345.67); 12345.7

System.out.println(1234.5); 1234.5

System.out.println(12345.6); 12345.6

System.out.println(123456.7); 123457

System.out.println(12345.0); 12345

System.out.println(123456.0); 123456

System.out.println(1234567.0); 1.23457e+006

System.out.println(123.00); 123

System.out.println(123.40); 123.4

Primitive Types: Floating Point

Highlighted

rows

rounded

Page 30: Chapter 3 Java Basics

Programming and Problem Solving With Java 30

Primitive Types: Floating PointFloating Point Operators

Operation Symbol Example Result

Addition + 5.4 + 2.0 7.4

Subtraction - 5.4 - 2.0 3.4

Multiplication * 5.4 * 2.0 10.8

Division / 5.4 / 2.0 2.7

Page 31: Chapter 3 Java Basics

Programming and Problem Solving With Java 31

Primitive Types: Floating PointFloating point precedence

Precedence Level Operation

High ()

Medium *, /

Low +, -

Page 32: Chapter 3 Java Basics

Programming and Problem Solving With Java 32

Primitive Types: Floating PointFloating point types

Float point ranges

Floating-point Type Size

float 4 bytes (32 bits)

double 8 bytes (64 bits)

Floating-point Type Smallest Value Largest Value

float 1.40129846432481707e-45 3.40282346638528860e+38

double 4.94065645841246544e-324 1.79769313486231570e+308

Page 33: Chapter 3 Java Basics

Programming and Problem Solving With Java 33

Primitive Types: Integer vs floating

Use integers for counting Use floating-point numbers for measuring

Page 34: Chapter 3 Java Basics

Programming and Problem Solving With Java 34

Using StringsString is a sequence of characters

Literal value: "This is a string"Java strings

Not primitive (built-in) typeStandard class

String operationsMany operations: length, substring, search, etc.Example

// Display the length of a string literalpublic class FindLength{ public static void main(String[] args) { System.out.println("This is a string literal".length()); }}

Page 35: Chapter 3 Java Basics

Programming and Problem Solving With Java 35

VariablesVariable: named location in memoryCan hold one value

floatNum(floating-point

variable)

6.72

intNum(integer variable)

437

Page 36: Chapter 3 Java Basics

Programming and Problem Solving With Java 36

VariablesEach variable like a

calculator memory Holds one value Can retrieve value many

times Storing a new value erases

oldDifferences from calculator

memory Can have many variables Variable can be one of many

types Each variable has a name

Page 37: Chapter 3 Java Basics

Programming and Problem Solving With Java 37

VariablesKinds of variables

Local InstanceClass (static)

Variable definitionsint count;int sum, limit;

Examplepublic class IllustrateVariables{ String anInstanceVariable; static int aStaticVariable; public static void main(String[] args) { int aLocalVariable; }}

Variable, schmariable

Page 38: Chapter 3 Java Basics

Programming and Problem Solving With Java 38

Variables: ParametersParameters are like local variables

Difference: initial value of parameter passed inclass SmartTurtle{ // drawSquare: Draws a square of the given size public void drawSquare(int size) { for (int i = 1; i <= 4; i++) { this.move(size); this.turnRight(90); } } …}

Counting variable of for statement is local variableScope restricted to for statement

Local variable i

Parameter size

Page 39: Chapter 3 Java Basics

Programming and Problem Solving With Java 39

Variable

Variables: AssignmentAssignment operator =

Stores value in a variableRead as "becomes", not "equals"Examples

int count;count = 25;count = sum;count = sum + 15;count = count + 1;

SyntaxVariable = Expression

= Expression

Page 40: Chapter 3 Java Basics

Programming and Problem Solving With Java 40

Variables: InitializationInitialization symbol =

OptionalGives variable its first value

Examplesint count = 0;double weight = 10.2;String firstName = "John", lastName = "Smith";

Only one variable initialized per valueint first, second, third = 25;

Uninitialized variables don't have a valueint count;System.out.println(count); // Wrong

Compiler outputTest.java:7: Variable count may not have been initialized.System.out.println(count); // Wrong

Page 41: Chapter 3 Java Basics

Programming and Problem Solving With Java 41

Variables: Assign vs InitializeAssignment & initialization use same symbolDifferent operations

// Demonstrates assignment and initialization

public class StringDemonstration{ public static void main(String[] args) { String firstName = "Linda"; // Initialize firstName String lastName; // No initial value String name; // No initial value

lastName = "Smith"; // Assign to lastName name = firstName; // Assign to name name = name + " " + lastName; // Assign to name again

System.out.println("Name is " + name); }} Name is Linda Smith

Page 42: Chapter 3 Java Basics

Programming and Problem Solving With Java 42

Variables: Assign & InitializeAssignment and initialization are operators

Not statements or commandsPart of expressionVery low precedence

= inside expressionsx = y = 0;

Same asx = (y = 0);

Both x and y get 0Associativity

Two of same operators in expressionTells which the computer executes first

PrecedenceLevel

Operation Associativity

High ()

Medium *, /, % left

Low +, - left

Very low = right

Page 43: Chapter 3 Java Basics

Programming and Problem Solving With Java 43

Variables: Increment & DecrementCan use assignment to increment

count = count + 1;

Or use increment operatorcount++; // Postfix version++count; // Prefix version

Difference between post- and pre-Postfix: increment after evaluating expression

int x = 0, y = 1;x = y++; // y is 2, x is 1

Prefix: increment before evaluating expressionint x = 0, y = 1;x = ++y; // y is 2, x is 2

Also post- and prefix decrement operators --count--;--count;

Page 44: Chapter 3 Java Basics

Programming and Problem Solving With Java 44

Variables: Displaying Values// Displays the average of four floating // point numbers

public class DisplayAverage{ public static void main(String[] args) { double firstNum = 10.0; double secondNum = 12.3; double thirdNum = 15.4; double fourthNum = 18.9;

double average;

average = (firstNum + secondNum + thirdNum + fourthNum) / 4;

System.out.println("The average is " + average); }}

Page 45: Chapter 3 Java Basics

Programming and Problem Solving With Java 45

ConstantsConstant is like a variable

Has nameHas value

Constant is unlike a variableValue can't change

DefiningMust define as a class (static) variableDefined in the class, outside of any method

static final double TARGET_SALES = 350000.0;

Makes program more readableSystem.out.println("Widget have sold " + (sales / TARGET_SALES * 100) + " percent of target sales");

Page 46: Chapter 3 Java Basics

Programming and Problem Solving With Java 46

Constants: UsesGive meaning to meaningless literal value

static final double TARGET_SALES = 350000.0;

Makes program easier to readConvention: ALL_CAPITAL_LETTERS for constants

Values that occur several times in a programNames of companies, departments, etc.

static final String BANK_NAME = "First National Bank";static final String BRANCH_NAME = "Springfield Branch";

Makes it easier to update the programHow about constants for 0 and 1?

static final int ONE = 1;…count = count + ONE;

No more readable than using literal value 1

Page 47: Chapter 3 Java Basics

Programming and Problem Solving With Java 47

Constants: Numeric LimitsPredefined constants for largest and smallest numbers

System.out.println("Range of int: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);System.out.println("Range of long: " + Long.MIN_VALUE + " to " + Long.MAX_VALUE);System.out.println("Range of float: " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);System.out.println("Range of double: " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);

OutputRange of int: -2147483648 to 2147483647Range of long: -9223372036854775808 to 9223372036854775807Range of float: 1.4013e-045 to 3.40282e+038Range of double: 2.22507e-308 to 1.79769e+308

Page 48: Chapter 3 Java Basics

Programming and Problem Solving With Java 48

InputMany programs require input from userInput devices

KeyboardMouseStylusScanner

Keyboard input is complex in JavaWill use Keyboard class for nowWill learn other techniques later

Page 49: Chapter 3 Java Basics

Programming and Problem Solving With Java 49

Input: Keyboard Classimport Keyboard;

public class DemonstrateKeyboardInput{ public static void main(String[] args) throws java.io.IOException { int height, width;

System.out.print("Enter height of rectangle: "); System.out.flush(); height = Keyboard.readInt();

System.out.print("Enter width of rectangle: "); System.out.flush(); width = Keyboard.readInt();

System.out.println("The area of the rectangle is " + (width * height)); }}

Enter height of rectangle: 4Enter height of rectangle: 4Enter width of rectangle:Enter height of rectangle: 4Enter width of rectangle: 3The area of the rectangle is 12

Enter height of rectangle:Enter height of rectangle: 4Enter width of rectangle: 3

Note use of exception

Page 50: Chapter 3 Java Basics

Programming and Problem Solving With Java 50

Input: Keyboard ClassMethods in Keyboard class

readInt() readByte() readShort() readLong() readFloat() readDouble() readString()

When control reaches Keyboard methodComputer waits for user to enter valueMethod returns value user typed

Page 51: Chapter 3 Java Basics

Programming and Problem Solving With Java 51

Input: PromptingPrompting message

Put before input methodTells user what to type

System.out.print() vs. System.out.println()print() message appears on same line as input

System.out.print("Enter first number: ");System.out.flush();firstNum = Keyboard.readDouble();

printlln() message on line above inputSystem.out.println("Enter second number:");secondNum = Keyboard.readDouble();

Enter second number:18

Enter first number: 24

Page 52: Chapter 3 Java Basics

Programming and Problem Solving With Java 52

Input: Keyboard Method PromptsPrompt message with System.out.print()

System.out.print("Enter first number: ");System.out.flush();firstNum = Keyboard.readDouble();

Prompt message with Keyboard.readxxx()Combine prompt with input method

firstNum = Keyboard.readDouble("Enter first number: ");

For numeric types, can force limitsage = Keyboard.readInt("Enter age: ", 0, 100);

For String, can force minimum and maximum length// Force user to enter at least 5 charactersname = Keyboard.readString("Enter name: ", 5);

// Force user to enter between 5 and 10 characterspassword = Keyboard.readString("Enter password: ", 5, 10);

Page 53: Chapter 3 Java Basics

Programming and Problem Solving With Java 53

Input Example: Safe Heart RateSafe heart rate for exercise, based on age

Maximum heart rate: 220 - ageSafe heart rate: 60% to 85% of maximum

Sample run*** Exercise Heart Rate Target ***

Enter your name: JohnEnter your age in years: 25

Maximum safe heart rate for John, age 25, is 195.You will get a good workout at a rate between 117 and 165.75.

Page 54: Chapter 3 Java Basics

Programming and Problem Solving With Java 54

Input Example: Safe Heart RateAlgorithm

Display the program's title Ask the user to type his or her age Maximum heart rate is 220 minus age Minimum workout rate is 0.6 times

maximum heart rate Maximum workout rate is 0.85 times

maximum heart rate Display the results

Page 55: Chapter 3 Java Basics

Programming and Problem Solving With Java 55

Input Example: Safe Heart Rate// This program finds the maximum heart rate, minimum// workout heart rate, and maximum workout heart rate, based on the// user's age.

import Keyboard;

public class SafeHeartRate{ static final double LOWER_WORKOUT_FACTOR = 0.6; static final double UPPER_WORKOUT_FACTOR = 0.85; static final int BASELINE = 220;

public static void main(String[] args) throws java.io.IOException { String name; int age, maximumRate; double minimumWorkoutRate, maximumWorkoutRate;

// Display program title System.out.println("*** Exercise Heart Rate Target ***"); System.out.println();

Page 56: Chapter 3 Java Basics

Programming and Problem Solving With Java 56

Input Example: Safe Heart Rate // Get user's name name = Keyboard.readString("Enter your name: "); // Get user's age age = Keyboard.readInt("Enter your age in years: ");

// Calculate heart rates maximumRate = BASELINE - age; minimumWorkoutRate = maximumRate * LOWER_WORKOUT_FACTOR; maximumWorkoutRate = maximumRate * UPPER_WORKOUT_FACTOR;

// Display results System.out.println("Maximum safe heart rate for " + name + ", age " + age + ", is " + maximumRate + "."); System.out.println("You will get a good workout at a rate " + "between " + minimumWorkoutRate + " and " + maximumWorkoutRate + "."); }}

Page 57: Chapter 3 Java Basics

Programming and Problem Solving With Java 57

Input Example: Loan PaymentLoan payment, based on amount, rate, length

Sample run*** Payment on a Loan ***

Enter the title of the loan: My Computer LoanEnter the amount of the loan: 1000Enter the interest rate: 0.05Enter the number of months: 24

Results for My Computer LoanFor a loan of 1000, interest rate of 0.05, over 24 months,the monthly payment is 72.4709.

months)rate 1(1

1

rate amount payment

Page 58: Chapter 3 Java Basics

Programming and Problem Solving With Java 58

Input Example: Loan PaymentConvert payment formula to Java

))months rate, 1(Math.pow/11rate)/( *amount (

)months rate, 1(Math.pow/11

rate amount

)months rate, 1(Math.pow1

1

rate amount

)rate 1(1

1

rate amount payment

months

Page 59: Chapter 3 Java Basics

Programming and Problem Solving With Java 59

Input Example: Loan PaymentAlgorithm

Display the program's titleGet the loan information from the user

Amount of the loan.Interest rate.Number of months.

Compute paymentDisplay the payment

Use floating-point variablesNeed to store dollars and cents

Page 60: Chapter 3 Java Basics

Programming and Problem Solving With Java 60

Input Example: Loan Payment// This program displays the monthly payment on a// loan, given the amount of the loan, the interest rate, and// the number of months of the loan

import Keyboard;

public class LoanPayment{ public static void main(String[] args) throws java.io.IOException { double amount, interestRate, numMonths, payment; String title;

// Present program title System.out.println("*** Payment on a Loan ***"); System.out.println();

// Get input title = Keyboard.readString("Enter the title of the loan: "); amount = Keyboard.readDouble("Enter the amount of the loan: "); interestRate = Keyboard.readDouble("Enter the interest rate: "); numMonths = Keyboard.readDouble("Enter the number of months: ");

Page 61: Chapter 3 Java Basics

Programming and Problem Solving With Java 61

Input Example: Loan Payment // Find the payment payment = (amount * interestRate) / (1 - (1 / Math.pow(1 + interestRate, numMonths)));

// Display results System.out.println(); System.out.println("Results for " + title + ":"); System.out.println("For a loan of " + amount + ", interest rate of " + interestRate + ", over " + numMonths + " months, "); System.out.println("the monthly payment is " + payment + "."); }}

Page 62: Chapter 3 Java Basics

Programming and Problem Solving With Java 62

Type Conversion: ImplicitAutomatic promotion from "narrow" to "wide" range

Exampledouble d = 4.2 * 2;

doublefloatlongintshortbyte

Page 63: Chapter 3 Java Basics

Programming and Problem Solving With Java 63

Type Conversion: Implicitdouble x = 2.5 + 5 / 2 - 1.25;

2.5 + 5 / 2 1.25-

Evaluate5 / 2 as 2

Evaluate2.5 + 2.0 as 4.5

Promote2 to 2.0

Evaluate4.5 - 1.25 as 3.25

=double x

Initialize x to3.25

Page 64: Chapter 3 Java Basics

Programming and Problem Solving With Java 64

Type Conversion: ExplicitProgrammer can control conversionCast: type name in parentheses

int intNum = (int) 123.45;

double doubleNum = 123.45;

System.out.println((short) doubleNum + 3);System.out.println((short) (doubleNum + 3));

Conversion to integer type makes program more efficient

Floating-point operations usually slower

(short) applies todoubleNum only

(short) applies todoubleNum + 3

Page 65: Chapter 3 Java Basics

Programming and Problem Solving With Java 65

Type Conversion: ExplicitConverting floating-point to integer

Cast: truncates digits to right of decimalMath.ceil(): closest integer greater or equalMath.floor(): closest integer less or equalMath.round(): closest integer

Example: -1.6 and 1.6

0.0-1.0-2.0 1.0 2.0

floorceil

1.6

floorceil

-1.6

round round

Page 66: Chapter 3 Java Basics

Programming and Problem Solving With Java 66

Type Conversion: ExplicitConverting other types to String

String.valueOf() converts any type to StringExample

// Demonstrates conversion of an integer to a String

public class IntToString{ public static void main(String[] args) { int number = 123456; String numberString = String.valueOf(Math.abs(number));

System.out.println("The number " + number + " has " + numberString.length() + " digits"); }}

Page 67: Chapter 3 Java Basics

Programming and Problem Solving With Java 67

Type Conversion: ExplicitEasier way to convert to String

Concatenate empty string to valueExample

// Demonstrates another way to convert an integer// to a String

public class IntToString2{ public static void main(String[] args) { int number = 123456; String numberString = "" + Math.abs(number);

System.out.println("The number " + number + " has " + numberString.length() + " digits"); }}

Page 68: Chapter 3 Java Basics

Programming and Problem Solving With Java 68

Ethics in ComputingEthics: Rules and standards a society agrees to live

byLawsCustomsMoral codes

Varies by cultures and societiesMost professions have rules of conductEthical rules in computing

Association of Computing Machinery (ACM)Data Processing Management Association (DPMA) Institute for Electronic and Electrical Engineers (IEEE)

Page 69: Chapter 3 Java Basics

Programming and Problem Solving With Java 69

Ethics in ComputingPunishment may result if rules not followed

Break laws Jail, fines, etc. Ignore professional ethics Professional censure

Positive reputation results from following laws and professional ethicsPerson of trust and integrityPerson who deals fairly and responsiblySteady, long-term rise in prestige,

responsbility, incomeProfessional should set example

for others to follow

Page 70: Chapter 3 Java Basics

Programming and Problem Solving With Java 70

Ethics in Computing: Software Piracy

Piracy: copying commercial software without permissionTheft -- against the law

HackingHacking: using someone else's

computer without permissionComputer Fraud and Abuse Act

(US) makes hacking illegalElectronic Communications Privacy Act (US)

makes interception of electronic communcation illegalMost other countries and US states have similar laws

Page 71: Chapter 3 Java Basics

Programming and Problem Solving With Java 71

Ethics in ComputingViruses

Virus: attaches to a program, then spreads when program runs

May do damage: destroy files, delete files, …Easy to write, but is a crimeGood practice to use virus protection

PlagiarismPlagiarism: submitting work of someone else as your ownEasy to do without meaning toShould credit work done by others

Page 72: Chapter 3 Java Basics

Programming and Problem Solving With Java 72

Ethics in Computing

Page 73: Chapter 3 Java Basics

Programming and Problem Solving With Java 73

Additional Features of JavaCompound assignment operators

Operator Example Equivalent to

+= x += 3; x = x + 3;

-= x -= 7; x = x - 7;

*= x *= 2; x = x * 2;

/= x /= 9; x = x / 9;

%= x %= 3; x = x % 3;