25 January 2013Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank...

Post on 28-Mar-2015

216 views 2 download

Tags:

transcript

25 January 2013 Birkbeck College, U. London 1

Introduction to Programming

Lecturer: Steve Maybank

Department of Computer Science and Information Systems

sjmaybank@dcs.bbk.ac.ukSpring 2013

Week 3: Variables and Number Types

Overview

Review of week 2: declaring variables

Number types Keyboard input Mathematical functions See Java for Everyone, Chapter 2

25 January 2013 Birkbeck College, U. London 2

Recall Variable Declaration

int cansPerPack = 6;

/*int: integer number type. All variables have a

type.=: assignmentcansPerPack: descriptive name in camel case.6: initial value*/

25 January 2013 Birkbeck College, U. London 3

Alternative Declaration

int cansPerPack; // variable declarationcansPerPack = 6; // initialisation

Always initialise a variable before using it,

even if there is a default initialisation.

25 January 2013 Birkbeck College, U. London 4

Example Code

int cansPerPack = 6;System.out.println(cansPerPack);int cansPerCrate = 4 * cansPerPack;

/* A variable can be initialised using an expression.

*/

25 January 2013 Birkbeck College, U. London 5

Number Types

25 January 2013 Birkbeck College, U. London 6

Type Description

int integer, range –231 to 231 -1

byte integer, range –128 to 127

short integer, range –215 to 215 -1

long integer, range –263 to 263 -1

double double precision floating point (15 decimal digits, range ±10308)

float single precision floating point (7 decimal digits, range ±1038). Now rarely used.

char character, encoded in Unicode

Variable Names

Consist of numbers, letters and underscore _ $ is legal, but reserved for names generated

by software tools Must begin with a letter or underscore Case sensitive Avoid reserved words By convention: class names begin with a

capital letter, variable names begin with a lower case letter

25 January 2013 Birkbeck College, U. London 7

Examples of Variable Names

25 January 2013 Birkbeck College, U. London 8

counter

counter67

largeNumber

large_Number

large Number

byte

6counter

counter?

days/month

Counter

cou67ter

IF

_counter

largenumber

$largeNumber

Conventionaland accepted bythe compiler

Not conventional butaccepted by the compiler

Rejected bythe compiler

Comments

double canVolume=0.355; //Litres in a can

/* This is a long comment */

/** This is a comment which explains thepurpose of a class.*/

25 January 2013 Birkbeck College, U. London 9

Example Program/** This program computes the volume in litres of a six-pack of soda

cans.*/public class Volume1{

public static void main(Strings[] args){

int cansPerPack = 6;double canVolume = 0.355; // Litres in a 12-ounce canSystem.out.print(“A six-pack of 12-ounce cans contains ”);System.out.print(cansPerPack * canVolume);System.out.println(“ litres.”);

}}

25 January 2013 Birkbeck College, U. London 10

Overflowint oneBillion = 1000000000;System.out.println(3 * oneBillion);

/* Output: -1294967296. No compile time error is flagged. No error message appears at run time.Solution: use type double but note round off errors and overflow in double, e.g. 10400.

*/

25 January 2013 Birkbeck College, U. London 11

Assignment of a Value to a Variable

int counter = 0;int increment = 1;counter = counter+1;counter++;counter- -;counter += 1;counter += increment;counter *= 2;

25 January 2013 Birkbeck College, U. London 12

Constantsfinal double BOTTLE_VOLUME=2;/* The reserved word final ensures that the

value of BOTTLE_VOLUME will never change. Use names for constants and avoid “magic numbers”, eg. compare the following.*/

double volume1=bottles * 2;double volume2=bottles * BOTTLE_VOLUME;

25 January 2013 Birkbeck College, U. London 13

Strings and Characters‘H`: character of type char.“H”: string containing a single character, namely ‘H`.

String greeting = “Harry”;char start = greeting.charAt(0); // Value of start is `H`; int count = Integer.parseInt(“34”);/* parseInt is a static method in the class java.lang.Integer.

It converts a string to the corresponding integer. */

25 January 2013 Birkbeck College, U. London 14

Recall Key Board Inputimport java.util.Scanner; // first line of program

Scanner in = new Scanner(System.in);/* create a Scanner object to read keyboard input */

System.out.print(“Enter the number of bottles: ”);// prompt

int bottles = in.nextInt(); // read integer input/* Type digits at key board, then press the enter or return

key */

25 January 2013 Birkbeck College, U. London 15

Types of Key Board InputSystem.out.print(“Enter the price in the form a.b where a

is the number of pounds and b is the number of pence: ”);

double unitPrice=in.nextDouble();

System.out.print(“Enter your first name: “);String name = in.next(); // input a single word, e.g. “John”

System.out.print(“Enter your full name: ”);String fullName = in.nextLine();/* input a whole line, e.g. “John Smith” */

25 January 2013 Birkbeck College, U. London 16

A Test of the Key Board Input

System.out.println(“Type an integer: ”);boolean test = in.hasNextInt();

if(test){

int i = in.nextInt();}else{

System.out.println(“error”);}

25 January 2013 Birkbeck College, U. London 17

Arithmetic Operators

25 January 2013 Birkbeck College, U. London 18

+ addition

- subtraction

* multiplication

/ division

% modulus

Multiplication and division take precedence over addition and subtraction.Use brackets to control the evaluation of expressions.If in any doubt, use brackets.

Examples

25 January 2013 Birkbeck College, U. London 19

Expression

Value

2+6/2 5

(2+6)/2 4

5/2 2

5%2 1

6.2/2 3.1

(2+6.0)/16

0.5

(2+6)*2+3

19

Powers and Roots

25 January 2013 Birkbeck College, U. London 20

Math function Method

x Math.sqrt(x)

x2 Math.pow(x,2)

xy, x>0 or x=0, y>0 or x<0, y integer

Math.pow(x,y)

Round x to nearest integer

Math.round(x)(long integer returned)

log10(x), x>0. Math.log10(x)

|x| Math.abs(x)

Conversion of Floating Point to Integer

double balance = total+tax;int dollars1 = (int) balance;

/* The value of balance is converted to an integer by discarding the fractional part. The operator (int) is a cast operator.

*/int dollars2=(int)(total + tax);

25 January 2013 Birkbeck College, U. London 21

Roundoff Errors/** This program demonstrates the effect of a round off error.*/public class RoundoffDemo{

public static void main(String[] args){

double price = 4.35;int cents = (int)(100 * price); // Should be 100*4.35=435System.out.println(cents); // Prints 434!

}/* 4.35 cannot be represented exactly as a number of type double

*/}

25 January 2013 Birkbeck College, U. London 22

API Application Programming

Interface: contains the classes and methods in the Java library.

The API documentation is at

http://java.sun.com/javase/7/docs/apiSee also JFE Appendix D.

25 January 2013 Birkbeck College, U. London 23