java basics

76
1 Java basics Chapter 2 Slides still stolen (and in a very exciting format!) Trey Kirk

Upload: munin

Post on 06-Jan-2016

20 views

Category:

Documents


0 download

DESCRIPTION

Java basics. Chapter 2 Slides still stolen (and in a very exciting format!) Trey Kirk. DisplayForecast.java. // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Java basics

1

Java basics

Chapter 2Slides still stolen (and in a very exciting format!)Trey Kirk

Page 2: Java basics

2

DisplayForecast.java

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}}

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} Three statements make up the action of method

main()

Method main() is part of class DisplayForecast

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} A method is a named piece of code that performs

some action or implements a behavior

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} An application program is required to have a

public static void method named main().

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} public, static, and void are keywords. They

cannot be used as names

public means the method is shareable

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} We will discuss static and void later

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} Java allows a statement to be made up of

multiple lines of text

Semicolons delimit one statement from the next

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} A class defines an object form. An object can

have methods and attributes

Keyword class indicates a class definition follows

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} A class like a method must have a name

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} A class like a method must have a name

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} Programs are read by people – make sure they are

readable.

Use whitespace, comments, and indentation to aid understanding

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} // indicates rest of the line is a comment

Comments are used to document authors, purpose, and program elements

Three comments

Page 3: Java basics

3

Indentation

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}}

Indentation indicates subcomponents

Method main() is part of DisplayForecast

Statements are part of method main()

Page 4: Java basics

4

Good whitespacing

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");

}} Whitespace separates program elements

Whitespace between program elements is ignored by Java

Whitespace

Page 5: Java basics

5

Bad whitespacing The same program without any whitespacing or comments:

public class DisplayForecast2 { public static void main (String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } }

Page 6: Java basics

6

Identifiers Identifiers are names for variables, classes, etc.

Good ones are compact, but inidicate what they stand for radius, width, height, length

Bad ones are either too long theRadiusOfTheCircle theWidthOfTheBoxThatIsBeingUsed the_width_of_the_box_that_is_being_used

Or too short a, b, c, d, e

Good identifiers will help the graders understand your program!

Page 7: Java basics

7

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); }}

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); }}

Keywords

// Authors: J. P. Cohoon and J. W. Davidson// Purpose: display a quotation in a console window

public class DisplayForecast {

// method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); }}

Some words are reserved, and can’t be used as identifiers

Page 8: Java basics

8

Capitalization Case matters!

public ≠ Public ≠ PUBLIC This is different than FORTRAN and BASIC This is the same as C/C++

You can use Public as a identifier Not recommended, though!

Page 9: Java basics

9

Statements A statement in Java is (usually) a single line

Example: System.out.println (“Hello world!”);

All statements must end with a semi-colon That tells Java that the statement is finished

Page 10: Java basics

1010

A bit of humor:A bit of humor:1989 Computer1989 ComputerAdvertisementAdvertisement

Guess the price!

Page 11: Java basics

1111

VariablesVariables

Page 12: Java basics

12

Defining variables We’ve seen variables before in math

y = mx + b Here y, m, x, and b can hold any value

To store things in a computer program, we also use variables

Example: int x = 5; Visualization: This defines an integer variable with value 5

The variable is x The type is int

5x

Page 13: Java basics

13

More on variables An integer variable can only hold integers

In other words, it can’t hold 4.3

To hold floating point values, we use the double type double d = 4.3;

The variable is d The type is double

4.3d

Page 14: Java basics

14

Assignment operator = Allows the memory location for a variable to be updated

Considerint j = 11;j = 1985;

Assignment operator = Allows the variable to be updated

Considerint j = 11;j = 1985;

Primitive variable assignment

11j

Expression to beevaluated

Name of previouslydefined object

target = expression ;

1985j

Page 15: Java basics

15

1a

1aSquared

Considerint a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

Considerint i = 0;i = i + 1;

Considerint asaRating;asaRating = 400;

Primitive variable assignment

5a

1aSquared

5a

25aSquared

0i 1i

-asaRating 400asaRating

int a = 1;int aSquared = a * a;a = 5;aSquared = a * a;

int i = 0;i = i + 1;

int asaRating;asaRating = 400;

Page 16: Java basics

16

19.28x

5.12y

5.12rememberX

5.12x

Primitive variable assignment

5.12x

19.28y

5.12x

19.28y

5.12rememberX

19.28x

19.28y

5.12rememberX

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Considerdouble x = 5.12;double y = 19.28;double rememberX = x; x = y; y = rememberX;

Page 17: Java basics

17

Printing variables To print a variable to the screen, put it in a

System.out.println() statement:

int x = 5; System.out.println (“The value of x is “ + x);

Important points: Strings are enclosed in double quotes If there are multiple parts to be printed, they are

separated by a plus sign

Page 18: Java basics

public class SolvingABC {

public static void main(String[] args) {

// variable definitions and initializationsint a = 3;int b = 12;int c = 6;int d = 1;

// calculate resultsdouble result1 = d * a;double result2 = c + 2 * a;double result3 = d - b / c;double result4 = c * b % c;double result5 = b / 2;

// display the resultsSystem.out.println();System.out.println("result1 : " + result1);System.out.println("result2 : " + result2);System.out.println("result3 : " + result3);System.out.println("result4 : " + result4);System.out.println("result5 : " + result5);System.out.println();

}}

From this week’s lab

Note that I don’t show a lot of comments so that the code will fit on a single slide

Also note all the semi-colons

Page 19: Java basics

19

Variable initialization Note that the following

int x; x = 5;

is (mostly) the same as the following:

int x = 5;

Page 20: Java basics

20

You can only declare variables once The following code will not work:

int x = 5; int x = 6;

Java can have only one variable named x So you can’t declare multiple variables with the same

name (we’ll see ways around this later in the semester)

Page 21: Java basics

2121

Today’s demotivatorsToday’s demotivators

Page 22: Java basics

2323

TypesTypes

Page 23: Java basics

24

Primitive variable types Java has 8 (or so) primitive types:

float double boolean char byte short int long

real numbers

integer numbers

two values: true and false

a single character

Also the void “type”, which we will see later

We’ll only be using half of the types in this course: int, double, boolean, and char

Page 24: Java basics

25

Primitive real (floating-point) types A float takes up 4 bytes of space

Has 6 decimal places of accuracy: 3.14159

A double takes up 8 bytes of space Has 15 decimal places of accuracy: 3.14159265358979

Always use doubles It will save you quite a headache!

Page 25: Java basics

26

Primitive integer types Consider a byte:

0 1 0 0 0 1 0 1

1 byte = 8 bits Each bit has two possibilities: 0 or 1

28 = 256 Thus, a byte can have any one of 256 values

A Java byte can have values from -128 to 127 From -27 to 27-1

C/C++ has unsigned versions; Java does not

Page 26: Java basics

27

Primitive integer types

Type Bytes Minimum value Maximum value

byte 1 -27=-128 27-1=127

short 2 -215=-32,768

215-1=32,767

int 4 -231=-2,147,483,648 231-1=2,147,483,647

long 8 -263=-9,223,372,036,854,775,808

263-1=9,223,372,036,854,775,807

Page 27: Java basics

28

Increment and decrement operators ++

Increments a number variable by 1 --

Decrements a numeric variable by 1

Considerint i = 4; // define++i;System.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i; // incrementSystem.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i); // displaySystem.out.print(++i);System.out.println(i++);System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i); // update then displaySystem.out.println(i++); System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i); System.out.println(i++); // display then update System.out.println(i);

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i); // display

++ Increments a number variable by 1

-- Decrements a numeric variable by 1

Considerint i = 4;++i;System.out.println(i);System.out.print(++i);System.out.println(i++);System.out.println(i);

4i 5i 6i 7i

Page 28: Java basics

2929

Why C++ was named C++Why C++ was named C++

The increment operator adds one to The increment operator adds one to the integer valuethe integer value– Or makes it ‘one better’Or makes it ‘one better’

So when Bjarne Stroustrup was So when Bjarne Stroustrup was making the successor to C, he was making the successor to C, he was making a ‘one better’ languagemaking a ‘one better’ language

Page 29: Java basics

30

Primitive character type All characters have a integer equivalent

‘0’ = 48 ‘1’ = 49 ‘A’ = 65 ‘a’ = 97

Thus, you can refer to ‘B’ as ‘A’+1

Page 30: Java basics

31

Primitive boolean type

The boolean type has only two values: true false

There are boolean-specific operators && is and || is or ! is not etc.

We’ll see those operators in a few slides

Page 31: Java basics

32

Variables must be declared before use The following code will not work:

x = 5; System.out.println (x);

Java requires you to declare x before you use it

Page 32: Java basics

33

Variable initialization Consider the following code:

int x;System.out.println(x);

What happens?

Error message: variable x might not have been initialized

Java also requires you to give x a value before you use it

Page 33: Java basics

34

Constants Consider the following:

final int x = 5;

The value of x can NEVER be changed! The value assigned to it is “final”

This is how Java defines constants

Constants have a specific naming scheme MILES_PER_KILOMETER All caps, with underscores for spaces

Page 34: Java basics

35

Expressions What is the value used to initialize expression

int expression = 4 + 2 * 5;

What value is displayed

System.out.println(5 / 2.0);

Java rules in a nutshell

Each operator has a precedence level and an associativity

Operators with higher precedence are done first

* and / have higher precedence than + and -

When floating-point is used the result is floating point

Page 35: Java basics

36

Question on expressions Does the following statement compute the average of double

variables a, b, and c? Why or why not?

double average = a + b + c / 3.0;

Page 36: Java basics

37

Java operators The following are the common operators for ints:

+ - / * % Division is integer division

6 / 2 yields 3 7 / 2 yields 3, not 3.5 Because everything is an int, the answer is an int

Modulus is % Returns the remainder 7 % 2 yields 1 6 % 2 yields 0

Floats and doubles use the same first four operators + - / * 7.0 / 2.0 yields 3.5 7.0 / 2 yields 3.5 7 / 2.0 yields 3.5 7 / 2 yields 3

Page 37: Java basics

38

Java operators Booleans have their own operators

&& is AND Only true when both operands are true true && true yields true false && true yields false

|| is OR True when either of the operands (or both) are true true || false yields true false || false yields false

! is NOT Changes the value !true yields false !false yields true

Page 38: Java basics

3939

New York DriversNew York Drivers

Page 39: Java basics

40

System.out.println Can print multiple things by using the + operator Let int i = 7; Example: System.out.println (“i = “ + i);

Prints i = 7

Can also have the statement on multiple linesSystem.out.println (

“hello world!”);

But can’t have the String on multiple linesSystem.out.println (

“hello world!”);

Page 40: Java basics

41

System.out.println System.out.println (“result: “ + 3/5);

What does it print? result: 0

System.out.println (“result: “ + 5 % 3); What does it print? result: 2

System.out.println (“result: “ + 3/5.0); What does it print? result: 0.6

System.out.println (“result: “ + 3+4.0); What does it print? result: 34.0

System.out.println (“result: “ + (3+4.0)); What does it print? result: 7.0

Page 41: Java basics

4242

Scanner usageScanner usage

Page 42: Java basics

43

Interactive programs Programs that interact with their users through statements

performing input and output

Page 43: Java basics

44

Reading in a value from the keyboard We will see this in more detail later in this slide set For now (and for lab 2), this is what you need to know

To read in values from the keyboard, you first have to create a Scanner object Don’t worry about what an object is, what a Scanner is, or

about creation of these things We’ll get to them later To do this, use the following code:

Scanner stdin = new Scanner (System.in);

Page 44: Java basics

45

Reading in more values from the keyboard You should have this only once in your program.

From then on, when you want to read in a value into a variable, use the following:

int x = stdin.nextInt();double d = stdin.nextDouble();

Or

x = stdin.nextInt();d = stdin.nextDouble();

Page 45: Java basics

46

Scanner usage exampleimport java.util.*;

public class ScannerUsage {public static void main (String args[]) {

Scanner stdin = new Scanner (System.in);

System.out.println ("Enter first value");int x = stdin.nextInt();

int y;System.out.println ("Enter second value");y = stdin.nextInt();

int z = x + y;System.out.println ("The sum of " + x + " and " +

y + " is " + z);}

}

Page 46: Java basics

4747

Program demo…Program demo…

ScannerUsage.javaScannerUsage.java

Note that all this code is available on the Note that all this code is available on the website!website!

Page 47: Java basics

48

How to make Java work with the Scanner class In Java 1.5, do a:

import java.util.*;

To create a new Scanner:Scanner stdin = new Scanner (System.in);

Page 48: Java basics

4949

Today’s demotivatorsToday’s demotivators

Page 49: Java basics

5050

Program ExamplesProgram Examples

Page 50: Java basics

51

Example program: temperature conversion// Purpose: Convert a Celsius temperature to Fahrenheit

public class CelsiusToFahrenheit {

// main(): application entry pointpublic static void main(String[] args) { // set Celsius temperature of interest int celsius = 28;

// convert to Fahrenheit equivalent int fahrenheit = 32 + ((9 * celsius) / 5);

// display result System.out.println("Celsius temperature"); System.out.println(" " + celsius); System.out.println("equals Fahrenheit temperature"); System.out.println(" " + fahrenheit);}

}

Page 51: Java basics

5252

Program demo…Program demo…

CelsiusToFahrenheit.javaCelsiusToFahrenheit.java

Page 52: Java basics

53

Computation Programmers frequently write small programs for computing

useful things

Example – body mass index (BMI) Measure of fitness

Ratio of person’s weight to the square of the person’s height Weight in is kilograms, height is in meters

Person of interest is 4.5 feet and weighs 75.5 pounds

Metric conversions Kilograms per pound 0.454 Meters per foot 0.3046

Page 53: Java basics

54

Program outline for BMI.java// Purpose: Compute BMI for given weight and height public class BMI { // main(): application entry point public static void main(String[] args) { // define constants // set up person's characteristics // convert to metric equivalents // perform bmi calculation // display result } }

Page 54: Java basics

55

// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

// define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

BMI.java: define constants

0.454KILOGRAMS_PER_POUND

0.3046METERS_PER_FOOT

Page 55: Java basics

56

BMI.java: personal characteristics

75.5weightInPounds

// set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height

// set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height

// set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height

4.5heightInFeet

Page 56: Java basics

57

BMI.java: convert to metric equivalents

34.2770metricWeight

// convert to metric equivalents

double metricWeight = weightInPounds * KILOGRAMS_PER_POUND;

double metricHeight = heightInFeet * METERS_PER_FOOT;

// convert to metric equivalents

double metricWeight = weightInPounds * KILOGRAMS_PER_POUND;

double metricHeight = heightInFeet * METERS_PER_FOOT;

// convert to metric equivalents

double metricWeight = weightInPounds * KILOGRAMS_PER_POUND;

double metricHeight = heightInFeet * METERS_PER_FOOT; 1.3706metricHeight

Page 57: Java basics

58

BMI.java: perform BMI calculation

// perform bmi calculation double bmi = metricWeight / (metricHeight *

metricHeight);

18.2439bmi

Page 58: Java basics

59

// display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi));

BMI.java: display result

// display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi));

Operator evaluation depend upon its operands

Math.round(bmi) is 18

18.2439bmi

Page 59: Java basics

public static void main(String[] args) { // define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046; // set up person's characteristics double weightInPounds = 75.5; // our person’s weight double heightInFeet = 4.5; // our person’s height // convert to metric equivalents double metricWeight = weightInPounds *

KILOGRAMS_PER_POUND; double metricHeight = heightInFeet * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weightInPounds + " lbs"); System.out.println(" height " + heightInFeet + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }

Page 60: Java basics

6161

Program demo…Program demo…

BMI.javaBMI.java

Page 61: Java basics

62

Common program elements Constant

Symbolic name for memory location whose value does not change KILOGRAMS_PER_POUND

Variable Symbolic name for memory location whose value can

change weightInPounds

Page 62: Java basics

6363

BMI CalculatorBMI Calculator

Page 63: Java basics

64

Program outline

import java.util.*;

// Purpose: Compute BMI for user-specified// weight and height

public class BMICalculator {

// main(): application entry pointpublic static void main(String[] args) {

// defining constants// displaying legend// set up input stream// get person's characteristics// convert to metric equivalents// perform bmi calculation// display result

}}

Interactive program for BMI Program outline

import java.util.*;

// Purpose: Compute BMI for user-specified// weight and height

public class BMICalculator {

// main(): application entry pointpublic static void main(String[] args) {

// defining constants// displaying legend// set up input stream// get person's characteristics// convert to metric equivalents// perform bmi calculation// display result

}}

Page 64: Java basics

public static void main(String[] args) { // define constants //...

// displaying legend System.out.println ("BMI Calculator\n");

// set up input stream Scanner stdin = new Scanner (System.in);

// get person's characteristics System.out.print("Enter weight (lbs): "); double weight = stdin.nextDouble();

System.out.print("Enter height (feet): "); double height = stdin.nextDouble();

// convert to metric equivalents double metricWeight = weight * KILOGRAMS_PER_POUND; double metricHeight = height * METERS_PER_FOOT;

// perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight);

// display result //...}

Page 65: Java basics

import java.util.*;class BMICalculator {

public static void main(String[] args) { // define constants final double KILOGRAMS_PER_POUND = 0.454; final double METERS_PER_FOOT = 0.3046;

// displaying legend System.out.println ("BMI Calculator\n");

// set up input stream Scanner stdin = new Scanner (System.in);

// get person's characteristics System.out.print("Enter weight (lbs): "); double weight = stdin.nextDouble();

System.out.print("Enter height (feet): "); double height = stdin.nextDouble(); // convert to metric equivalents double metricWeight = weight * KILOGRAMS_PER_POUND; double metricHeight = height * METERS_PER_FOOT; // perform bmi calculation double bmi = metricWeight / (metricHeight * metricHeight); // display result System.out.println("A person with"); System.out.println(" weight " + weight + " lbs"); System.out.println(" height " + height + " feet"); System.out.println("has a BMI of " + Math.round(bmi)); }}

Page 66: Java basics

6767

Program demo…Program demo…

BMICalculator.javaBMICalculator.java

Page 67: Java basics

68

Scanner APIpublic Scanner(InputStream in) // Scanner(): convenience constructor for an

// InputStream

public Scanner(File s) // Scanner(): convenience constructor for a filename

public int nextInt() // nextInt(): next input value as an int

public short nextShort() // nextShort(): next input value as a short

public long nextLong() // nextLong(): next input value as a long

public double nextDouble() // nextDouble(): next next input value as a double

public float nextFloat() // nextFloat(): next next input value as a float

public String next() // next(): get next whitespace-free string

public String nextLine() // nextLine(): return contents of input line buffer

public boolean hasNext() // hasNext(): is there a value to next

Page 68: Java basics

6969

CastingCasting

Page 69: Java basics

70

Casting Consider the following code

double d = 3.6;int x = Math.round(d);

Java complains (about loss of precision). Why?

Math.round() returns a long, not an int So this is forcing a long value into an int variable

How to fix thisdouble d = 3.6;int x = (int) Math.round(d);

You are telling Java that it is okay to do this This is called “casting” The type name is in parenthesis

Page 70: Java basics

71

More casting examples Consider

double d = 3.6;int x = (int) d;

At this point, x holds 3 (not 4!) This truncates the value!

Considerint x = 300;byte b = (byte) x;System.out.println (b);

What gets printed? Recall that a byte can hold values -128 to 127 44! This is the “loss of precision”

Page 71: Java basics

7272

More on println()More on println()

Page 72: Java basics

73

System.out.println()

public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943.");}

Class System supplies objects that can print and read values

System variable out references the standard printing object Known as the standard output stream

Variable out provides access to printing methods print(): displays a value println(): displays a value and moves cursor to the next

line

Page 73: Java basics

74

print() vs. println() What do these statements output?

System.out.print (“foo”);System.out.println (“bar”);System.out.println ();System.out.println (“foo”);System.out.println (“bar”);

Output

foobar

foobar

Page 74: Java basics

75

Escape sequences Java provides escape sequences for printing special

characters \b backspace \n newline \t tab \r carriage return \\ backslash \" double quote \' single quote

Page 75: Java basics

76

Escape sequences What do these statements output?

System.out.println("Person\tHeight\tShoe size");System.out.println("=========================");System.out.println("Hannah\t5‘1\"\t7");System.out.println("Jenna\t5'10\"\t9");System.out.println("JJ\t6'1\"\t14");

Output

Person Height Shoe size=========================Hannah 5‘1" 7Jenna 5'10" 9JJ 6'1" 14

Page 76: Java basics

7777

What we wish computers could What we wish computers could dodo