using classes eng

24
8/16/2019 Using Classes Eng http://slidepdf.com/reader/full/using-classes-eng 1/24 Using Classes and Objects Dr Jonas Lundberg, office B3024 [email protected] Slides and examples are available at Moodle November 8, 2014 The Software Technology Group Using Classes and Objects  1(24)

Upload: simone-stefani

Post on 05-Jul-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 124

Using Classes and Objects

Dr Jonas Lundberg office B3024

JonasLundberglnuse

Slides and examples are available at Moodle

November 8 2014

The Software Technology Group

Using Classes and Objects 1(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 224

Lecture 3

Classes vs Objects

Creating objects

A few common library classes String

Scanner StringBuilder Random Math DecimalFormat

Reading instructions NoneBut please take a look at the Java API documentation for the abovementioned classes

Exercises Assignment 1 12-16

The Software Technology Group

Using Classes and Objects 2(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 324

Classes and Objects

A class defines properties of a given type of objects We say that an object O A is an instance of class A

class BankAccount Object 1 Object 2 Object 3

Owner Jonas Henrik Nils

No 4758-8696 3246-9744 5432-2347

Balance 34345kr 8456kr 97654kr

Primitive types (eg int) have simple values (eg 237)and operations (eg addition)

Classes (eg BankAccount) have more complex values

(eg Jonas4758-869634345kr) and more complex operations(eg method updateBalance(int balance))

We use classes to model entities (eg BankAccount Student) that cannot be described with just a simple value

Classes and Objects The Software Technology Group

Using Classes and Objects 3(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 424

Example

This class

can generate these objects

Volvo

850

AAA111

Jaguar

XJS

XXX999

Ford

FocusCCC333

This type of diagrams are called UML diagrams We will discuss them inthe next course

Classes and Objects The Software Technology Group

Using Classes and Objects 4(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 524

Objects

A class is a blue-print describing objects

Each object has

state behavior identity (rArr Each object is unique)

Example a simple Lock object

States Open or Closed Behavior Open lock or Close lock

Behavior rArr what objects can do rArr given by the methods

Classes and Objects The Software Technology Group

Using Classes and Objects 5(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 624

Creating Objects in Java

Each object belongs to (is defined by) a class

Example Create a String object

String name = new String(Jonas)

Scanner scan = new Scanner(Systemin)

= new String(Jonas)

rArr we create a new String object with state Jonas

String name =

rArr variable name holds a reference to the String object Jonas

Notice Strings are used very often rArr Java have therefore simplified the

string creation

String name = new String(Jonas) Standard

String name = Jonas Simplified (but identical)

Classes and Objects The Software Technology Group

Using Classes and Objects 6(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 724

Creating Objects in General

Assume class MyClass

Creating a MyClass object

MyClass variableName = new MyClass( )

The reserved word new rArr a new object is created The text after new (in this case MyClass) defines the type of the object to

be created

Some terminology We say that

the created object is an instance of class MyClass the variable variableName holds a reference to (or points to ) the

newly created object

Classes and Objects The Software Technology Group

Using Classes and Objects 7(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 2: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 224

Lecture 3

Classes vs Objects

Creating objects

A few common library classes String

Scanner StringBuilder Random Math DecimalFormat

Reading instructions NoneBut please take a look at the Java API documentation for the abovementioned classes

Exercises Assignment 1 12-16

The Software Technology Group

Using Classes and Objects 2(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 324

Classes and Objects

A class defines properties of a given type of objects We say that an object O A is an instance of class A

class BankAccount Object 1 Object 2 Object 3

Owner Jonas Henrik Nils

No 4758-8696 3246-9744 5432-2347

Balance 34345kr 8456kr 97654kr

Primitive types (eg int) have simple values (eg 237)and operations (eg addition)

Classes (eg BankAccount) have more complex values

(eg Jonas4758-869634345kr) and more complex operations(eg method updateBalance(int balance))

We use classes to model entities (eg BankAccount Student) that cannot be described with just a simple value

Classes and Objects The Software Technology Group

Using Classes and Objects 3(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 424

Example

This class

can generate these objects

Volvo

850

AAA111

Jaguar

XJS

XXX999

Ford

FocusCCC333

This type of diagrams are called UML diagrams We will discuss them inthe next course

Classes and Objects The Software Technology Group

Using Classes and Objects 4(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 524

Objects

A class is a blue-print describing objects

Each object has

state behavior identity (rArr Each object is unique)

Example a simple Lock object

States Open or Closed Behavior Open lock or Close lock

Behavior rArr what objects can do rArr given by the methods

Classes and Objects The Software Technology Group

Using Classes and Objects 5(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 624

Creating Objects in Java

Each object belongs to (is defined by) a class

Example Create a String object

String name = new String(Jonas)

Scanner scan = new Scanner(Systemin)

= new String(Jonas)

rArr we create a new String object with state Jonas

String name =

rArr variable name holds a reference to the String object Jonas

Notice Strings are used very often rArr Java have therefore simplified the

string creation

String name = new String(Jonas) Standard

String name = Jonas Simplified (but identical)

Classes and Objects The Software Technology Group

Using Classes and Objects 6(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 724

Creating Objects in General

Assume class MyClass

Creating a MyClass object

MyClass variableName = new MyClass( )

The reserved word new rArr a new object is created The text after new (in this case MyClass) defines the type of the object to

be created

Some terminology We say that

the created object is an instance of class MyClass the variable variableName holds a reference to (or points to ) the

newly created object

Classes and Objects The Software Technology Group

Using Classes and Objects 7(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 3: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 324

Classes and Objects

A class defines properties of a given type of objects We say that an object O A is an instance of class A

class BankAccount Object 1 Object 2 Object 3

Owner Jonas Henrik Nils

No 4758-8696 3246-9744 5432-2347

Balance 34345kr 8456kr 97654kr

Primitive types (eg int) have simple values (eg 237)and operations (eg addition)

Classes (eg BankAccount) have more complex values

(eg Jonas4758-869634345kr) and more complex operations(eg method updateBalance(int balance))

We use classes to model entities (eg BankAccount Student) that cannot be described with just a simple value

Classes and Objects The Software Technology Group

Using Classes and Objects 3(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 424

Example

This class

can generate these objects

Volvo

850

AAA111

Jaguar

XJS

XXX999

Ford

FocusCCC333

This type of diagrams are called UML diagrams We will discuss them inthe next course

Classes and Objects The Software Technology Group

Using Classes and Objects 4(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 524

Objects

A class is a blue-print describing objects

Each object has

state behavior identity (rArr Each object is unique)

Example a simple Lock object

States Open or Closed Behavior Open lock or Close lock

Behavior rArr what objects can do rArr given by the methods

Classes and Objects The Software Technology Group

Using Classes and Objects 5(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 624

Creating Objects in Java

Each object belongs to (is defined by) a class

Example Create a String object

String name = new String(Jonas)

Scanner scan = new Scanner(Systemin)

= new String(Jonas)

rArr we create a new String object with state Jonas

String name =

rArr variable name holds a reference to the String object Jonas

Notice Strings are used very often rArr Java have therefore simplified the

string creation

String name = new String(Jonas) Standard

String name = Jonas Simplified (but identical)

Classes and Objects The Software Technology Group

Using Classes and Objects 6(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 724

Creating Objects in General

Assume class MyClass

Creating a MyClass object

MyClass variableName = new MyClass( )

The reserved word new rArr a new object is created The text after new (in this case MyClass) defines the type of the object to

be created

Some terminology We say that

the created object is an instance of class MyClass the variable variableName holds a reference to (or points to ) the

newly created object

Classes and Objects The Software Technology Group

Using Classes and Objects 7(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 4: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 424

Example

This class

can generate these objects

Volvo

850

AAA111

Jaguar

XJS

XXX999

Ford

FocusCCC333

This type of diagrams are called UML diagrams We will discuss them inthe next course

Classes and Objects The Software Technology Group

Using Classes and Objects 4(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 524

Objects

A class is a blue-print describing objects

Each object has

state behavior identity (rArr Each object is unique)

Example a simple Lock object

States Open or Closed Behavior Open lock or Close lock

Behavior rArr what objects can do rArr given by the methods

Classes and Objects The Software Technology Group

Using Classes and Objects 5(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 624

Creating Objects in Java

Each object belongs to (is defined by) a class

Example Create a String object

String name = new String(Jonas)

Scanner scan = new Scanner(Systemin)

= new String(Jonas)

rArr we create a new String object with state Jonas

String name =

rArr variable name holds a reference to the String object Jonas

Notice Strings are used very often rArr Java have therefore simplified the

string creation

String name = new String(Jonas) Standard

String name = Jonas Simplified (but identical)

Classes and Objects The Software Technology Group

Using Classes and Objects 6(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 724

Creating Objects in General

Assume class MyClass

Creating a MyClass object

MyClass variableName = new MyClass( )

The reserved word new rArr a new object is created The text after new (in this case MyClass) defines the type of the object to

be created

Some terminology We say that

the created object is an instance of class MyClass the variable variableName holds a reference to (or points to ) the

newly created object

Classes and Objects The Software Technology Group

Using Classes and Objects 7(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 5: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 524

Objects

A class is a blue-print describing objects

Each object has

state behavior identity (rArr Each object is unique)

Example a simple Lock object

States Open or Closed Behavior Open lock or Close lock

Behavior rArr what objects can do rArr given by the methods

Classes and Objects The Software Technology Group

Using Classes and Objects 5(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 624

Creating Objects in Java

Each object belongs to (is defined by) a class

Example Create a String object

String name = new String(Jonas)

Scanner scan = new Scanner(Systemin)

= new String(Jonas)

rArr we create a new String object with state Jonas

String name =

rArr variable name holds a reference to the String object Jonas

Notice Strings are used very often rArr Java have therefore simplified the

string creation

String name = new String(Jonas) Standard

String name = Jonas Simplified (but identical)

Classes and Objects The Software Technology Group

Using Classes and Objects 6(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 724

Creating Objects in General

Assume class MyClass

Creating a MyClass object

MyClass variableName = new MyClass( )

The reserved word new rArr a new object is created The text after new (in this case MyClass) defines the type of the object to

be created

Some terminology We say that

the created object is an instance of class MyClass the variable variableName holds a reference to (or points to ) the

newly created object

Classes and Objects The Software Technology Group

Using Classes and Objects 7(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 6: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 624

Creating Objects in Java

Each object belongs to (is defined by) a class

Example Create a String object

String name = new String(Jonas)

Scanner scan = new Scanner(Systemin)

= new String(Jonas)

rArr we create a new String object with state Jonas

String name =

rArr variable name holds a reference to the String object Jonas

Notice Strings are used very often rArr Java have therefore simplified the

string creation

String name = new String(Jonas) Standard

String name = Jonas Simplified (but identical)

Classes and Objects The Software Technology Group

Using Classes and Objects 6(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 724

Creating Objects in General

Assume class MyClass

Creating a MyClass object

MyClass variableName = new MyClass( )

The reserved word new rArr a new object is created The text after new (in this case MyClass) defines the type of the object to

be created

Some terminology We say that

the created object is an instance of class MyClass the variable variableName holds a reference to (or points to ) the

newly created object

Classes and Objects The Software Technology Group

Using Classes and Objects 7(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 7: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 724

Creating Objects in General

Assume class MyClass

Creating a MyClass object

MyClass variableName = new MyClass( )

The reserved word new rArr a new object is created The text after new (in this case MyClass) defines the type of the object to

be created

Some terminology We say that

the created object is an instance of class MyClass the variable variableName holds a reference to (or points to ) the

newly created object

Classes and Objects The Software Technology Group

Using Classes and Objects 7(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 8: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 824

Method Calls

The object behavior is defined by the operations they can perform Each class contains a set of methods that defines the operations

The class String has among others the following operations

String(String str) Constructor Creates a new string object

char charAt(int index) Returns the character in position index int length() Returns the number of characters in the string toLowerCase() Returns a new string with only lower case letters toUpperCase() Returns a new string with only upper case letters substring(int offset int endIndex) Returns a new string

containing the characters in position offset to endIndex-1

Examples of method calls

String str = Jonas Create a string object

int l = strlength() calls length() on str ==gt l=5

char c = strcharAt(2) calls charAt(int index) ==gt c = rsquonrsquo

Classes and Objects The Software Technology Group

Using Classes and Objects 8(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 9: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 924

Example ndash Stringsjava

public class Strings

public static void main(String [] args) String abc = new String(rdquoabcdefghrdquo)int length = abclength () Number of characters char first = abccharAt(0) Get first character Systemout println (abc+rdquotLength = rdquo+length+rdquotFirst = rdquo+first)

String name = rdquoJonas LundbergrdquoString sub = namesubstring(210) Characters 3 till 10 String upper = nametoUpperCase() To upper case letters Systemout println (name+rdquotSub = rdquo+sub+rdquotUpper = rdquo+upper)

Output

abcdefgh Length = 8 First = a

Jonas Lundberg Sub = nas Lund Upper = JONAS LUNDBERG

Classes and Objects The Software Technology Group

Using Classes and Objects 9(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 10: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1024

The Java Class Library

Java comes with a big class library containing more than 6000 classes

The library classes is a resource often used during programming

Some classes are general and are used extensively(for example String Scanner)

Other classes are very specific and are rarely used

(for example AudioInputStream which is used for reading sound files) The class library is divided into packages For example

javalang (The most usual classes (String System)) javaio (Classes about file handling (File)) javautil (Commonly used help classes (Scanner)) javaxswing (Graphical user interfaces)

If you unambiguously want to denote a class you give its qualified name

(full name)

Qualified name packageNameclassName

(for example javautilScanner javaioFile)

The Java Class Library The Software Technology Group

Using Classes and Objects 10(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 11: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1124

Using the Class Library Use javautilScanner rArr We have to import the package javautil

package chap2 The class ScannerIntro belongs to package chap2

import java util Scanner

lowast A program to test the Scanner class lowast public class ScannerIntro

public static void main(String [] args) lowast Create a Scanner reading from the keyboard lowast Scanner scan = new Scanner(Systemin)

import javautilScanner rArr makes the class Scanner available

Alternatively import javautil rArr makes all classes in javautil available

The package javalang is is imported automatically rArr Its classes (for exampleString) are always available

Ctrl-Shift-O rArr organize imports rArr automatic generation of importstatements

The Java Class Library The Software Technology Group

Using Classes and Objects 11(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 12: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1224

Java API Documentation

The Javas class library rArr Java Application Programming InterfacerArr Java API

Information about the Java class libraryrArr Java API documentation Online on the Internet

httpdocsoraclecomjavase7docsapi To be downloaded

httpwwworaclecomtechnetworkjavajavasedownloads

(Choose Java SE 7 Documentation)

This information is invaluable mdash absolutely necessary for anyJava programming

The Java Class Library The Software Technology Group

Using Classes and Objects 12(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 13: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1324

The Class StringBuilder

Strings in Java (objects of the class String) are constantsrArr Can not be changed after they have been created(For example you can not add characters at the end of the string)

If you want to manipulate the contents of a string use the classjavalangStringBuilder

StringBuilder is a flexible string (sequence of characters) makingit possible to Add characters one by one (Method append) Remove characters (Method deleteCharAt) Add at a given position (Method insert) Change characters (a substring) (Method replace) Overwrite a character (Method setCharAt) Convert to an ordinary string (Method toString)

and many more See the Java API documentation for moreinformation

Some Common Classes The Software Technology Group

Using Classes and Objects 13(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 14: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1424

Example ndash StringBuildersjava

public class StringBuilders

public static void main(String [] args) StringBuilder sb = new StringBuilder() Create an empty StringBuilder sbappend(rsquoarsquo) Add rsquoarsquo == gt sb = asbappend(rsquobrsquo) Add rsquobrsquo == gt sb = ab sbappend(rdquoCDEFGrdquo) Add rsquoCDEFGrsquo == gt sb = abCDEFG

String str = sbtoString () Convert to string Systemout println ( str ) Print minusout abCDEFG

sb insert (0 rsquoXrsquo) Add X first == gt sb = XabCDEFG sbsetCharAt(2rsquoZrsquo) Overwrite position 2 with rsquo Zrsquo == gt sb = XaZCDEFG sb reverse () Reverse the order of all characters == gt sb = GFEDCZa

str = sbtoString () Convert to string Systemout println ( str ) Print minusout GFEDCZaX

Note StringBuilders are indexed First position has index 0 (zero)

Some Common Classes The Software Technology Group

Using Classes and Objects 14(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 15: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1524

The Class Random

The class javautilRandom is a random number generator for

integers real numbers boolean

Random belongs to the package javautil rArr we need to make an import

Some methods nextInt(int n) rArr random integer between 0 and (n-1) nextDouble()rArr random double between 00 and 10 nextBoolean()rArr random boolean true or false

Note nextDouble() takes no input and gives a number between 0 and 1

Q Random real numbers between 1 and 100A Multiply with 99 (rArr 0 to 99) and add 1 (rArr 1 to 100)

Random rand = new random()double d = 1 + 99lowastrandnextDouble() Double between 1 and 100

Some Common Classes The Software Technology Group

Using Classes and Objects 15(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 16: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1624

Example ndash RandomNumbersjavapublic static void main(String [] args)

lowast Create a random number generator lowast Random rand = new Random()

int myInt = randnextInt(100) Random number between 0 and 99 Systemout println (rdquoRandom integer rdquo+ myInt)

double myReal = randnextDouble() Random number between 00 and 10 Systemout println (rdquoRandom real number rdquo+ myReal)

myReal = 500 + 500lowastrandnextDouble() Random real between 500 and 1000 Systemout println (rdquoAnother real number rdquo+ myReal)

boolean myBool = randnextBoolean() true or false Systemout println (rdquoRandom boolean rdquo+ myBool)

OutputRandom integer 35

Random real number 0707255066301434

Another real number 9053598211981803

Random boolean true

Some Common Classes The Software Technology Group

Using Classes and Objects 16(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 17: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1724

The Class Math and Static MethodsRandom r = new Random() Create Random object

= r nextInt (100) Call the method nextInt on the object that r refers t

Ordinary methods are called on objects (instances of a class)

Such methods are therefore sometimes called instance methods

The Class Math

The class javalangMath contains several static methods

double d = Mathsqrt(2) sqrt == gt square root Systemout println (rdquoThe square root of 2 rdquo+d)

d = Mathpow(d2) pow(mn) == gt m raised to the power of nSystemout println (rdquod raised to the power of 2 rdquo+d)

Static methods are called on a class Such methods are therefore sometimes called class methods

The class Math contains a big number of mathematical functions

For example logarithms powers (raised to) trigonometric functions (sine

cosine) absolute values round off (Mathround(double d)) etc

Some Common Classes The Software Technology Group

Using Classes and Objects 17(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 18: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1824

Formatting Screen Output The methods println and print in the class System give correct but

not always good looking print-outs You might for example want to decide whether to use a decimal point or a

decimal comma or how many decimal digits should be printed

Java has a number of help classes to make formatted outputs

javatextNumberFormat adjust to different countries For example

Good looking percentage print outs 02512 rArr 2512 Good looking currency print outs 67257 rArr 6725 kr

ie correct rounding and rdquocorrectrdquo currency(The settings of the computer rArr a country rArr a currency)(Sweden uses decimal comma while other countries (England US) usedecimal point)

The class javatextDecimalFormat gives you the possibility to decidehow real number should be printed

You can also use the method printf in the class System to configureyour own printouts

Read more in section 36Some Common Classes The Software Technology Group

Using Classes and Objects 18(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 19: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 1924

Ex NumberFormat ndash NumberFormattingjavadouble tax =025 Tax on food

double milkPrice = 875 Price for milk double noTax = (1minustax)lowastmilkPrice Price without tax

lowast Nonminusformatted print out lowast Systemout println (rdquoPrice for milk rdquo+milkPrice)Systemout println (rdquoPrice ( excl tax ) rdquo+noTax)

lowast Create formatting object lowast

NumberFormat moneyFormat = NumberFormatgetCurrencyInstance()

lowast Formatted printout lowast Systemout println (rdquonPrice for milk rdquo+moneyFormatformat(milkPrice))Systemout println (rdquoPrice ( excl tax ) rdquo+moneyFormatformat(noTax))

Output

Price for milk 875

Price (excl tax) 65625

Price for milk 875 krPrice (excl tax) 656 kr (Print out in US $656)

This holds for a computer with Swedish settings

currency formatting rArr decimal comma instead of decimal point 2 decimals currency text rdquokrrdquo

Some Common Classes The Software Technology Group

Using Classes and Objects 19(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 20: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2024

Ex DecimalFormat ndash ThreeDecimalsjava

import java text DecimalFormat

public class ThreeDecimals public static void main(String [] args)

double d = 803 2666666Systemout println (rdquoExact rdquo+d)

DecimalFormat dFormat = new DecimalFormat(rdquo0rdquo) Three decimals String three decimals = dFormatformat(d) Apply formatting on d Systemout println (rdquoThree Decimals rdquo+three decimals) rdquo2667rdquo

Printminusout

Exact 26666666666666665Three Decimals 2667

When we create the formatter we provide a pattern (0) deciding the number of

decimals to be used We then use the method format each time we want to format a

given double Notice format returns a string

Some Common Classes The Software Technology Group

Using Classes and Objects 20(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 21: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2124

Wrapper Classes

All primitive types have their corresponding classes For example

int rArr javalangInteger double rArr javalangDouble char rArr javalangCharacter

Such classes are called wrapper classes

The wrapper classes contain static methods that sometimes are veryuseful For example

IntegerparseInt(String s) Converts string 123 to integer 123 IntegertoString(int n) Converts integer 12345 to string 12345 CharacterisDigit(char ch) true if ch is a digit CharacterisLetter(char ch) true if ch is a letter CharacterisUpperCase(char ch) true if ch is an upper case letter CharacterisWhitespace(char ch) true if ch is a space or tab CharactertoUpperCase(char ch) Corresponding upper case letter CharactergetNumericValue(char ch) Converts rsquo7rsquo to 7 (char-to-digit ) and many others

You will need the wrapper classes in assignment 2 and 3

Some Common Classes The Software Technology Group

Using Classes and Objects 21(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 22: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2224

Problem Solving The computer will not solve the problem for you

It will do exactly what you tell it to do It just does it faster without getting bored or exhausted

rArr You must solve the problem by yourself

You should have a concrete solution idea before you start implementing

Basic Algorithm for Problem Solving

1 Understand the problem Look up things you are not sure about2 Solve the problem manually (Paper and Pen) in a few special cases

3 Implement the solution (in small steps)rArr Write 2-4 lines of code execute and print out intermediate results to verifythat it works

More implementation advices

Initially do not spend time on making print-outs look nice

Focus on solving the hard part of the problem

Also replace time consuming Provide a line of text with hard coded

String inputText = An example of a user input text

While implementing be efficient and donrsquot waste time on user inputoutput

Some Common Classes The Software Technology Group

Using Classes and Objects 22(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 23: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2324

Problem Solving (Example) Compute BMIProblem Write a program which comutes the BMI (Body Mass Index) for a person

Scanner in = new Scanner(Systemin)Systemoutprint(Give your length in meters ) Step 1 Read length

double length = innextDouble()

Systemoutprintln(Length + length) Diagnostics remove later on

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()

Systemoutprintln(Weight + weight) Diagnostics remove later on

OK assume Step 1-2 are working then comment it away and continue to work withfix length and weight rArr speed up testing process

Systemoutprint(Give your weight in kilograms ) Step 2 Read weight

double weight = innextDouble()Systemoutprintln(Weight + weight) Diagnostics remove later on

double length = 183 Fix values to be replaced with user

double weight = 806 input (above) when everything works

Continue here

Some Common Classes The Software Technology Group

Using Classes and Objects 23(24)

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)

Page 24: Using Classes Eng

8162019 Using Classes Eng

httpslidepdfcomreaderfullusing-classes-eng 2424

Before Next Lecture (In General) Read the sections in the book Try to understand all examples

Read the lecture slides Try to understand all examples(Download the examples and try them in Eclipse if not complete slides)

Work on daily set of exercises ndash Assign 1 task 12-16

Problems Ask your teaching assistant (practical meetings Moodle) or Jonas(lectures)

Why a procedure like this Gives an uniform work load no heavy peaks at deadlines or exams

Effective use of teacher resources

Nice to go home by 6 pm feeling you have done a good days work

More advices

Do not sit home by yourself mdash study in groups (or have Skype contact) avoid getting stuck on details much more fun easier to really get started (when you have made an appointment with

somebody) Danger when working in groups someone else solves all the problems

Some Common Classes The Software Technology Group

Using Classes and Objects 24(24)