• No results found

Computer Project (Movie Ticketing System)

N/A
N/A
Protected

Academic year: 2021

Share "Computer Project (Movie Ticketing System)"

Copied!
51
0
0

Loading.... (view fulltext now)

Full text

(1)

Given By: Paras Khurana

School: Strawberry Fields

World School

Class: 10-A

Year: 2013-14

(2)

I would like to express my special thanks of gratitude to my

teacher Mrs. Smita Satyarthi as well as our principal Mrs.

Sangeeta Sekhon who gave me the golden opportunity to do

this wonderful project on the topic programming in java (movie

ticketing system), which also helped me in doing a lot of

Research and i came to know about so many new things. I am

really thankful to them.

Secondly i would also like to thank my parents and friends who

helped me a lot in finishing this project within the limited time.

And giving me everything I required including the moral support

that I can finish the project on time.

(3)

Project Question

1. Data types in java.

2. Decision making statements

3. What are different types of IO

streams? Explain with the help of

examples.

4. Exception handling

5. Build an application that allows an

operator to book the tickets for his

selected movie, book his snacks and

print the bill amount. The bill can be for

matted to display the customer’s details

and the net amount.

(4)

CONTENTS

TOPIC

PAGE NO.

INTRODUCTION

1

DATA TYPES IN

JAVA

2-14

DECISION MAKING

STATEMENTS

15-20

IO STREAMS IN

JAVA

21-26

EXCEPTION

HANDLING

27-31

PROGRAM

(MOVIE

TICKETING

SYSTEM

32-47

BIBLIOGRAPHY

48

(5)

Introduction

Java is a general-purpose, concurrent, class-based, object-oriented computer programming

language that is specifically designed to have as few implementation dependencies as possible. It is

intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java applications are

typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers. Java was originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle

Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The

language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.

The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance with the

specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java (bytecode compiler), GNU Class

path (standard libraries), and IcedTea-Web (browser plugin for applets).

BlueJ is an integrated development environment (IDE) for the Java programming language, developed mainly for educational purposes, but also suitable for small-scale software development. BlueJ was developed to support the learning and teaching of object-oriented programming, and its design differs from other development environments as a result. The main screen graphically shows the class structure of an application under development (in an UML-like diagram), and objects can be interactively created and tested. This interaction facility, combined with a clean, simple user interface, allows easy experimentation with objects under development. Object-oriented concepts (classes, objects, communication through method calls) are represented visually and in its interaction design in the

(6)
(7)

1.

Data types are predefined by the Java language.

2.

Predefined data types are reserved keyword so we cannot use them as variable

name inside program/application.

3.

Primitive values do not share state with other primitive values.

4.

Total Number of Primitive Data Types in Java Programming is 8.

5.

All Primitive Data Types have respective Wrapper Classes i.e. Integer is wrapper

class for primitive type int.

Data Types:

Type

Contains

Default

Size

Boolean

true or false

false

1 bit

char

Unicode Character

u0000

16 bits

byte

Signed Integer

0

8 bits

short

Signed Integer

0

16 bits

int

Signed Integer

0

32 bits

long

Signed Integer

0

64 bits

float

Floating Number

0.0

32 bit

(8)

Integer Data Types:

1. Integer Data Type is used to store integer value.

2. Integer Data Type is Primitive Data Type in Java Programming Language.

3. Integer Data Type have respective Wrapper Class – “Integer“.

4. Integer Data Type is able to store both unsigned and signed integer values so Java

opted signed, unsigned concept of C/C++.

Integer Data Type can have 4 types of Values these are listed

below in the table

-Name Width Range

long

64

–9,223,372,036,854,775,808 to

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

int

32

–2,147,483,648 to 2,147,483,647

short

16

–32,768 to 32,767

byte

8

–128 to 127

5. Literals for integers consist of a sequence of digits. Most programming languages

disallow use of commas for digit grouping, although Fortran (77, 90, and above,

fixed form source but not free form source) allows embedded spaces,

and Perl, Ruby, Java and D allow embedded underscores. Negation is indicated by

a minus sign (−) before the value. Examples of integer literals are:

42

10000

(9)

Example: Declaring Integer Variable in Java

Programming

Class IntDemo

{

Public

static

void

main

(String

args

[])

{

int

number

=0

;

System

.

out

.

println

("

Number:

"

+

number

)

;

}

}

Explanation:

1.

Primitive Variable can be declared using “int” keyword.

2. Though Integer contain default Initial Value as 0, still we have assign 0 to show

assignment in Java.

3.

“+” operator is used to concatenate 2 strings.

4. Integer is converted into String internally and then two strings are concatenated.

Floating-Point Data Type:

1. Floating Data Type is used to store float value.

2. Floating Data Type is Primitive Data Type in Java Programming Language.

3. Floating Data Type have respective Wrapper Class – “Float or Double“.

(10)

Float Data Type Can store 2 types of Values these are listed below -

1. Float

2. Double

float

Variables of this type can have values from -3.4E38 (-3.4 * 1038) to +3.4E38

(+3.4 * 1038) and occupy 4 bytes in memory. Values are represented with

approximately 7 decimal digits accuracy

double Variables of this type can have values from -1.7E308 (-1.7 * 10308) to

+1.7E308 (+1.7 * 10308) and occupy 8 bytes in memory. Values are

represented with approximately 17 decimal digits accuracy. The smallest

non-zero value that you can have is roughly (4.9 * 10–324).

Example : Declaring float Variable in Java Programming

Class FloatDemo

{

public

static

void

main

(

String

args

[])

{

float

fval

=

10.0f

;

System

.

out

.

println

(

"

Total Number :

"

+

fval

)

;

}

}

Float Type : Some Notes

 In Java any value declared with decimal point is by default of type double.

Suppose we have to assign float value then we must use „f‟ or „F‟ literal to

specify that current value is “Float”.

Specify “E” or “e” for values which contain exponent.

How to Declare float Variable

(11)

How to Declare Double Variable

Class FloatDemo

{

public

static

void

main

(

String

args

[])

{

double

d1

=

10

;

System

.

out

.

println

(

"

Total Number :

"

+

fval

)

;

}

}

 We have assigned integer value to the Double . (i.e we are assigning lower

value of inside bigger variable , no need to typecast )

 double keyword is used to declare double variable.

Character Data Types:

1. In Java, the data type used to store characters is char.

2. Character is 16 bits wide in Java.

3. Java uses Unicode to represent characters.

4. Java support lot of Unicode symbols from many more human languages for this

purpose, it requires 16 bits.

5. The range of a char is 0 to 65,536.

6. There are no negative chars.

What is Unicode ?

Unicode defines a fully international character set that can represent all of the

characters found in all human languages.

Example 1 : Integer Value Assigned to Character Data Type

(12)

public

static

void

main

(

String

args

[])

{

char

ch

;

ch

=

'M'

;

System

.

out

.

println

(

"

Character is :

"

+

ch

)

;

}

}

Output :

Character is

:

M

Example 2 : Integer Value Assigned to Character Data Type

// Demonstrate char data type.

class

CharDemo

{

public

static

void

main

(

String

args

[])

{

char

ch1

,

ch2

;

ch1

=

88

;

// code for X

ch2

=

'Y'

;

System

.

out

.

print

(

"

ch1 and ch2:

"

)

;

System

.

out

.

println

(

ch1

+

""

+

ch2

)

;

}

}

Output :

ch1

and

ch2

:

X Y

Example 3 : Incrementing Character Variable

class

CharDemo2

{

public

static

void

main

(

String

args

[])

{

char

ch1

;

(13)

System

.

out

.

println

(

"

ch1 contains

"

+

ch1

)

;

ch1

++

;

// increment ch1

System

.

out

.

println

(

"

ch1 is now

"

+

ch1

)

;

}

}

Output :

ch1 contains P

ch1 is now Q

Boolean Data Type :

1. Boolean is

primitive data type in Java

.

2. Boolean data type is used for

logical values

.

3. Boolean data type can have two possible values :

true or false

.

4. Boolean is the type

returned by all relational operators

5. Boolean is the type required

by the conditional expressions

used in control

statements such as if and for.

6.

“Boolean” is wrapper class for “boolean” primitive data type.

How to Declare & Display Boolean Variable ?

public

static

void

main

(

String

args

[])

{

boolean b1

,

b2

,

b3

;

b1

=

true

;

// Assigning Value

b2

=

false

;

// Assigning Value

b3

=

b2

;

// Assigning Variable

System

.

out

.

println

(

b1

)

;

// Printing Value

System

.

out

.

println

(

b2

)

;

// Printing Value

System

.

out

.

println

(

b3

)

;

// Printing Value

(14)

}

Output:

true

false

false

Different Ways of Using Boolean Value :

Way 1 : Inside If Statement

Boolean Value is used to check whether condition is true or not.

public

static

void

main

(

String

args

[])

{

boolean b

;

b

=

true

;

if

(

b

==

true

)

{

System

.

out

.

println

(

"

I am True

"

)

;

}

}

Way 2 : Comparing Two Numbers

class

Demo

{

public

static

void

main

(

String

args

[])

{

boolean b

;

b

=

(

10

>

6

)

;

if

(

b

)

(15)

System

.

out

.

println

(

"

10 > 6

"

)

;

}

}

}

We can use boolean value to hold the result Comparison operators. Here 10 >

6 therefore true will be stored in boolean variable

In Java a reference data type is a variable that can contain the reference or an

address of dynamically created object. These type of data type are not predefined

like primitive data type. The reference data types

are arrays, classes and interfaces that are made and handle according to a

programmer in a java program which can hold the three kind of values as:

class type:

As you know that Java is an object-oriented programming language where an object is

a variable, associated with methods that is described by a class. The name of a class is

treated as a type in a java program, so that you can declare a variable of an

object-type, and a method which can be called using that object- type variable.

array type

// Points to an array instance

class type

// Points to an object or a class instance

interface type

// Points to an object and a method, which is

implemented to the corresponding interface

(16)

Whenever a variable is created, a reference to an object is also created using the name

of a class for its type i.e. that variable can contain either null or a reference to an object

of that class. It is not allowed to contain any other kinds of values. Such type is

called reference types in Java. The object becomes an instance when the memory is

allocated to that object using new keyword. In addition, array typesare reference

types because these are treated as objects in Java. For example:

class Fruit {

fColor(){....}

fSize(){....}

};Fruit mango;

Fruit banana;

...

In the given example the Fruit is a class that has the reference variables as mango &

banana through which we can call

the behaviors associated with that class as mango.fColor(); within the main method of

the super class.

Array Type:

An array is a special kind of object that contains values called elements. The java

array enables the user to store the values of the same type in contiguous memory

allocations. The elements in an array are identified by an integer index which initially

starts from 0 and ends with one less than number of elements available in the array.

All elements of an array must contain the same type of value i.e. if an array is a type of

integer then all the elements must be of integer type. It is areference data

type because the class named as Array implicitly extendsjava.lang.Object. The

(17)

DataType [] variable1,

variable2, ...variableN;

DataType [] variable = new

DataType [ArraySize];

DataType [] variable = {item 1,

item 2,...item n};

For example:

int [] a = new int [10];

String [] b =

{"reference","data",

"type"};

In the first statement, an array variable "a" is declared of integer data type that holds

the memory spaces according to the size of int. The index of the array starts

from a[0] and ends with a[9]. Thus, the integer value can be assigned for each or a

particular index position of the array.

In the second statement, the array "b" is declared of string data type that has the

enough memory spaces to directly holds the three string values. Thus each value is

assigned for each index position of the array.

Interface Type:

Java provides an another kind of reference data type or a mechanism to

support multiple inheritance feature called an interface. The name of an interface

can be used to specify the type of a reference. A value is not allowed to be assign to a

variable declared using an interface type until theobject implements the

(18)

When a class declaration implements an interface, that class inherits all of the variables

and methods declared in that interface. So the implementations for all of the methods

declared in the interface must be provided by that class. For example, Java provides an

interface called ActionListener whose method named actionPerformed() is used to

handle the different kind of event . Java also provides a class called Thread that

implements Runnable interface.

Thus the following assignment can be allowed:

Runnable r;

r = new

Thread();

(19)

There are two types of decision making statements in Java. They are:

if statements

switch statements

The if Statement:

A if statement consists of a Boolean expression

followed by one or more statements.

Syntax:

The syntax of a if statement is:

if(Boolean_expression) {

//Statements will execute if the Boolean

expression is true }

If the Boolean expression evaluates to true then the

block of code inside the if statement will be executed. If not the first set of code after the

end of the if statement (after the closing curly brace) will be executed.

Example:

public class Test {

public static void main(String args[]){ int x = 10;

if( x < 20 ) {

System.out.print("This is if statement"); }

} }

(20)

This is if statement

The if...else Statement:

An if statement can be followed by an

optional

else

statement, which executes when the

Boolean expression is false.

Syntax:

The syntax of an if...else is:

if(Boolean_expression) {

//Executes when the Boolean expression is

true }else {

//Executes when the Boolean expression is

false }

Example:

public class Test {

public static void main(String args[]){ int x = 30;

if( x < 20 ){

System.out.print("This is if statement"); }else{

System.out.print("This is else statement"); }

} }

This would produce the following result:

This is else statement

The if...else if...else

Statement:

An if statement can be followed by an

optional

else if...else

statement, which is very

useful to test various conditions using single

if...else if statement.

(21)

When using if , else if , else statements there are few points to keep in mind.

An if can have zero or one else's and it must come after any else if's.

An if can have zero to many else if's and they must come before the else.

Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

The syntax of an if...else…if is:

if(Boolean expression 1) {

//Executes when the Boolean expression 1 is true

}

else if(Boolean expression 2) {

//Executes when the Boolean expression 2 is true

}

else if(Boolean expression 3) {

//Executes when the Boolean expression 3 is true

} else {

//Executes when the none of the above condition is true.

}

Example:

public class Test {

public static void main(String args[]) {

int x = 30; if( x == 10 ) {

System.out.print("Value of X is 10"); }

else if( x == 20 ) {

System.out.print("Value of X is 20"); }

else if( x == 30 ) {

System.out.print("Value of X is 30"); }

else {

System.out.print("This is else statement"); }

(22)

} }

This would produce the following result:

Value of X is 30

Nested if...else Statement:

It is always legal to nest if-else statements which means you can use one if or else if

statement inside another if or else if statement.

Syntax:

The syntax for a nested if...else is as follows:

if(Boolean_expression 1)

{

//Executes when the Boolean expression 1 is true

if(Boolean_expression 2) {

//Executes when the Boolean expression 2 is true }

}

You can nest

else if...else

in the similar way as we have nested

if

statement.

Example:

public class Test {

public static void main(String args[]){ int x = 30;

int y = 10; if( x == 30 ){ if( y == 10 ){

System.out.print("X = 30 and

Y = 10");

} } } }

This would produce the following result:

X = 30 and Y = 10

(23)

A

switch

statement allows a variable to be tested for equality against a list of values.

Each value is called a case, and the variable being switched on is checked for each

case.

Syntax:

The syntax of switch is:

switch(expression) { case value : //Statements break; //optional case value : //Statements break; //optional

//You can have any number of case statements.

default : //Optional //Statements }

The following rules apply to a switch statement:

The variable used in a switch statement can only be a byte, short, int, or char.

You can have any number of case statements within a switch. Each case is followed by

the value to be compared to and a colon.

The value for a case must be the same data type as the variable in the switch and it

must be a constant or a literal.

When the variable being switched on is equal to a case,

the statements following that case will execute until

a

break

statement is reached.

When a

break

statement is reached, the switch

terminates, and the flow of control jumps to the next line

following the switch statement.

Not every case needs to contain a break. If no break

appears, the flow of control will

fall through

to subsequent

cases until a break is reached.

A

switch

statement can have an optional default case,

which must appear at the end of the switch. The default

case can be used for performing a task when none of the

cases is true. No break is needed in the default case.

(24)
(25)

The java.io package contains class needed to perform input and output (I/O) in Java. All

these streams represent an input source and an output destination. The stream in the

java.io package supports many data such as primitives, Object, localized characters,

etc.

A stream can be defined as a sequence of data. The InputStream is used to read data

from a source and the OutputStream is used for writing data to a destination.

Java does provide strong, flexible support for I/O as it relates to files and networks.

Reading Console Input:

Java input console is accomplished by reading from

System.in

. To obtain a

character-based stream that is attached to the console, you wrap

System.in

in

a

BufferedReader

object, to create a character stream. Here is most common syntax to

obtain BufferedReader:

BufferedReader

br =

new

BufferedReader

(

new

InputStreamReader

(

System

.

in

));

Once BufferedReader is obtained, we can use read( ) method to reach a character or

readLine( ) method to read a string from the console.

Reading Characters from Console:

To read a character from a BufferedReader, we would read( ) method whose sytax is as

follows:

int

read( )

throws

IOException

Each time that read( ) is called, it reads a character from the input stream and returns it

as an integer value. It returns .1 when the end of the stream is encountered. As you can

see, it can throw an IOException.

The following program demonstrates read( ) by reading characters from the console

until the user types a "q":

(26)

import

java.io.*;

public

class

BRRead

{

public

static

void

main(

String

args[])

throws

IOException

{

char

c;

// Create a BufferedReader using System.in

BufferedReader

br =

new

BufferedReader

(

new

InputStreamReader

(

System

.

in

));

System

.

out

.println(

"Enter characters, 'q' to quit."

);

// read characters

do

{

c = (

char

) br.read();

System

.

out

.println(c);

}

while

(c !=

'q'

);

}

}

Here is a sample run:

Enter

characters,

'q'

to quit.

123abcq

1

2

3

a

b

c

q

Reading Strings from Console:

To read a string from the keyboard, use the version of readLine( ) that is a member of

the BufferedReader class. Its general form is shown here:

String

readLine( )

throws

IOException

The following program demonstrates BufferedReader and the readLine( ) method. The

program reads and displays lines of text until you enter the word "end":

// Read a string from console using a BufferedReader.

import

java.io.*;

public

class

BRReadLines

{

public

static

void

main(

String

args[])

throws

IOException

{

(27)

BufferedReader

br =

new

BufferedReader

(

new

InputStreamReader

(

System

.

in

));

String

str;

System

.

out

.println(

"Enter lines of text."

);

System

.

out

.println(

"Enter 'end' to quit."

);

do

{

str = br.readLine();

System

.

out

.println(str);

}

while

(!str.equals(

"end"

));

}

}

Here is a sample run:

Enter

lines of text.

Enter

'end'

to quit.

This

is

line one

This

is

line one

This

is

line two

This

is

line two

end

end

Writing Console Output:

Console output is most easily accomplished with

print( )

and

println( )

, described

earlier. These methods are defined by the class

PrintStream

which is the type of the

object referenced by

System.out

. Even though System.out is a byte stream, using it for

simple program output is still acceptable.

(28)

Reading and Writing Files:

Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream and FileOutputStream,

File Input Stream:

This stream is used for reading data from the files. Objects can be created using the

keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to

read the file.:

InputStream

f =

new

FileInputStream

(

"C:/java/hello"

);

Following constructor takes a file object to create an input stream object to read the file.

First we create a file object using File() method as follows:

File

f =

new

File

(

"C:/java/hello"

);

InputStream

f =

new

FileInputStream

(f);

Once you have

InputStream

object in hand, then there is a list of helper methods which

can be used to read to stream or to do other operations on the stream.

(29)

1

public void close() throws IOException{}

This method closes the file output stream. Releases any system resources

associated with the file. Throws an IOException.

2

protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method

of this file output stream is called when there are no more references to this

stream. Throws an IOException.

3

public int read(int r)throws IOException{}

This method reads the specified byte of data from the InputStream. Returns an

int. Returns the next byte of data and -1 will be returned if it's end of file.

4

public int read(byte[] r) throws IOException{}

This method reads r.length bytes from the input stream into an array. Returns the

total number of bytes read. If end of file -1 will be returned.

5

public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an

int.

File Output Stream:

FileOutputStream is used to create a file and write data into it. The stream would create

a file, if it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to

write the file:

OutputStream

f =

new

FileOutputStream

(

"C:/java/hello"

)

Following constructor takes a file object to create an output stream object to write the

file. First, we create a file object using File() method as follows:

File

f =

new

File

(

"C:/java/hello"

);

OutputStream

f =

new

FileOutputStream

(f);

Once you have

OutputStream

object in hand, then there is a list of helper methods,

which can be used to write to stream or to do other operations on the stream.

SN Methods with Description

1

public void close() throws IOException{}

This method closes the file output stream. Releases any system resources

associated with the file. Throws an IOException.

(30)

This method cleans up the connection to the file. Ensures that the close method

of this file output stream is called when there are no more references to this

stream. Throws an IOException.

3

public void write(int w)throws IOException{}

This methods writes the specified byte to the output stream.

4

public void write(byte[] w)

Writes w.length bytes from the mentioned byte array to the OutputStream.

Example:

Following is the example to demonstrate InputStream and OutputStream:

import

java.io.*;

public

class

fileStreamTest{

public

static

void

main(

String

args[]){

try

{

byte

bWrite [] = {11,21,3,40,5};

OutputStream

os =

new

FileOutputStream

(

"test.txt"

);

for

(

int

x=0; x < bWrite.length ; x++){

os.write( bWrite[x] );

// writes the bytes

}

os.close();

InputStream

is

=

new

FileInputStream

(

"test.txt"

);

int

size =

is

.available();

for

(

int

i=0; i< size; i++){

System

.

out

.

print

((

char

)

is

.read() +

" "

);

}

is

.close();

}

catch

(

IOException

e){

System

.

out

.

print

(

"Exception"

);

}

}

}

The above code would create file test.txt and would write given numbers in binary

format. Same would be output on the stdout screen.

(31)

An exception is a problem that arises during the execution of a program. An exception

can occur for many different reasons, including the following:

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has

run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and

others by physical resources that have failed in some manner.

Categories of exceptions:

Checked exceptions:

A checked exception is an exception that is typically a user error

or a problem that cannot be foreseen by the programmer. For example, if a file is to be

opened, but the file cannot be found, an exception occurs. These exceptions cannot

simply be ignored at the time of compilation.

Runtime exceptions:

A runtime exception is an exception that occurs that probably

could have been avoided by the programmer. As opposed to checked exceptions,

runtime exceptions are ignored at the time of compilation.

Errors:

These are not exceptions at all, but problems that arise beyond the control of

the user or the programmer. Errors are typically ignored in your code because you can

rarely do anything about an error. For example, if a stack overflow occurs, an error will

arise. They are also ignored at the time of compilation.

Catching Exceptions:

A method catches an exception using a combination of the

try

and

catch

keywords. A

try/catch block is placed around the code that might generate an exception. Code within

a try/catch block is referred to as protected code, and the syntax for using try/catch

looks like the following:

(32)

try

{

//Protected code

}

catch

(

ExceptionName

e1)

{

//Catch block

}

A catch statement involves declaring the type of exception you are trying to catch. If an

exception occurs in protected code, the catch block (or blocks) that follows the try is

checked. If the type of exception that occurred is listed in a catch block, the exception is

passed to the catch block much as an argument is passed into a method parameter.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the

3rd element of the array which throws an exception.

// File Name : ExcepTest.java

import

java.io.*;

public

class

ExcepTest

{

public

static

void

main(

String

args[]){

try

{

int

a[] =

new

int

[2];

System

.

out

.println(

"Access element three :"

+ a[3]);

}

catch

(

ArrayIndexOutOfBoundsException

e){

System

.

out

.println(

"Exception thrown :"

+ e);

}

System

.

out

.println(

"Out of the block"

);

}

}

This would produce the following result:

Exception

thrown :java.lang.

ArrayIndexOutOfBoundsException

: 3

Out

of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch

blocks looks like the following:

try

{

(33)

}

catch

(

ExceptionType1

e1)

{

//Catch block

}

catch

(

ExceptionType2

e2)

{

//Catch block

}

catch

(

ExceptionType3

e3)

{

//Catch block

}

The previous statements demonstrate three catch blocks, but you can have any number

of them after a single try. If an exception occurs in the protected code, the exception is

thrown to the first catch block in the list. If the data type of the exception thrown

matches ExceptionType1, it gets caught there. If not, the exception passes down to the

second catch statement. This continues until the exception either is caught or falls

through all catches, in which case the current method stops execution and the

exception is thrown down to the previous method on the call stack.

Example:

Here is code segment showing how to use multiple try/catch statements.

try

{

file =

new

FileInputStream

(fileName);

x = (

byte

) file.read();

}

catch

(

IOException

i)

{

i.printStackTrace();

return

-1;

}

catch

(

FileNotFoundException

f)

//Not valid!

{

f.printStackTrace();

return

-1;

}

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using

the

throws

keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you

just caught, by using the

throw

keyword. Try to understand the different in throws and

throw keywords.

(34)

import

java.io.*;

public

class

className

{

public

void

deposit(

double

amount)

throws

RemoteException

{

// Method implementation

throw

new

RemoteException

();

}

//Remainder of class definition

}

A method can declare that it throws more than one exception, in which case the

exceptions are declared in a list separated by commas. For example, the following

method declares that it throws a RemoteException and an InsufficientFundsException:

import

java.io.*;

public

class

className

{

public

void

withdraw(

double

amount)

throws

RemoteException

,

InsufficientFundsException

{

// Method implementation

}

//Remainder of class definition

}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally

block of code always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to

execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try

{

//Protected code

}

catch

(

ExceptionType1

e1)

{

//Catch block

}

catch

(

ExceptionType2

e2)

{

//Catch block

}

catch

(

ExceptionType3

e3)

{

(35)

//Catch block

}

finally

{

//The finally block always executes.

}

Example:

public

class

ExcepTest

{

public

static

void

main(

String

args[]){

int

a[] =

new

int

[2];

try

{

System

.

out

.println(

"Access element three :"

+ a[3]);

}

catch

(

ArrayIndexOutOfBoundsException

e){

System

.

out

.println(

"Exception thrown :"

+ e);

}

finally

{

a[0] = 6;

System

.

out

.println(

"First element value: "

+a[0]);

System

.

out

.println(

"The finally statement is

executed"

);

}

}

}

This would produce the following result:

Exception

thrown :java.lang.

ArrayIndexOutOfBoundsException

: 3

First

element value: 6

The

finally

statement

is

executed

Note the following:

A catch clause cannot exist without a try statement.

It is not compulsory to have finally clauses when ever a try/catch block is present.

The try block cannot be present without either catch clause or finally clause.

(36)

The Java Project Program

(Movie Ticketing System)

import java.io.*;

public class movies

{

static double bill;

static int c,type,d,flag;

static int e,type1,f;

static int g,type2,h; //Initialising all the required variables

static int i,type3,j;

static int quan;

static String l,n[],k;

static int m;

static String s,s1,s2,s3;

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

{

String a,b;String ch="";

String n[]=new String[4];

n[0]="burger";

n[1]="nachos";

n[2]="coke";

n[3]="popcorn";

BufferedReader buf=new BufferedReader(new

InputStreamReader(System.in));

do

{

System.out.println("--- WELCOME TO FUN CINEMAS ONLINE

BOOKING COUNTER ---");

System.out.println(" PLEASE SELECT THE MOVIE YOU WOULD LIKE TO

WATCH: ");

System.out.println("\n");

System.out.println("1. IRON MAN 3 ");

System.out.println("2. FAST AND FURIOUS 6 ");

System.out.println("3. GO GOA GONE "); //Here the movie is being selected

System.out.println("4. MAN OF STEEL "); System.out.println("\n");

System.out.println("TYPE THE NAME OF THE MOVIE YOU WANT TO WATCH IN CAPILTAL LETTERS");

try {

ch=buf.readLine(); //an expected error that the user enters something else instead of the movie

(37)

catch(IOException e1) {

System.out.println("Movie not running"); //handling of the exception }

if(ch.equalsIgnoreCase("IRON MAN 3")) {

System.out.println("\nPROCESSING YOUR REQUEST"); for(int z=0;z<1000000000;z++) { } System.out.println("\f"); IM3(); }

if(ch.equalsIgnoreCase("FAST AND FURIOUS 6")) {

System.out.println("\nPROCESSING YOUR REQUEST"); for(int z=0;z<1000000000;z++)

{ }

System.out.println("\f"); //calling of the function corresponding to the movie selected

FAF6(); }

if(ch.equalsIgnoreCase("GO GOA GONE")) {

System.out.println("\nPROCESSING YOUR REQUEST"); for(int z=0;z<1000000000;z++) { } System.out.println("\f"); GGG(); } if(ch.equalsIgnoreCase("MAN OF STEEL")) {

System.out.println("\nPROCESSING YOUR REQUEST"); for(int z=0;z<1000000000;z++) { } System.out.println("\f"); MOS(); } System.out.println("\n\n");

System.out.println("DO YOU WANT TO BOOK SOME SNACKS:"); System.out.println("\n\n");

System.out.println("TYPE 'Y' FOR YES OR PRESS ANY OTHER KEY"); a=buf.readLine();

System.out.println("\nPROCESSING YOUR REQUEST"); for(int z=0;z<1000000000;z++)

{ }

System.out.println("\f");

if(a.equalsIgnoreCase("y")) //checking whether the user wants to buy some snacks or not

{

SNACKS(); }

(38)

System.out.println("\n\n");

System.out.println("*** **** ***** COPY OF THE RECIEPT IS: ***** **** ***"); System.out.println("MOVIE: "+ch);

System.out.println("NO. OF TICKETS: "+d); //displaying of the bill

do {

System.out.print("THE SNACKS BOOKED ARE: "); for(m=0;m<1;m++) { if(s.equalsIgnoreCase(n[m])) { flag=0; System.out.print(n[m]); break; } } for(m=1;m<2;m++) { if(s1.equalsIgnoreCase(n[m])) { flag=0; System.out.print(", "+n[m]); break; } } for(m=2;m<3;m++) { if(s2.equalsIgnoreCase(n[m])) { flag=0; System.out.print(", "+n[m]); break; } } for(m=3;m<4;m++) { if(s3.equalsIgnoreCase(n[m])) { flag=0; System.out.println(", "+n[m]); break; } } }while(flag!=0); System.out.println("\nPAY Rs. "+bill);

System.out.println("~~~~~~~~~~ TYHANK YOU FOR WATHCHING MOVIES WITH FUN CINEMAS ~~~~~~~~~~");

System.out.println("DO YOU WANT TO BOOK TICKET FOR ANY OTHER MOVIE:"); System.out.println("\n\n");

System.out.println("TYPE 'Y' FOR YES OR PRESS ANY OTHER KEY"); //checking whether the user wants to buy any tother movie ticket or not b=buf.readLine();

(39)

}

while(b.equalsIgnoreCase("y")); }

public static void IM3()throws IOException {

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

System.out.println("--- WHAT TIMING OF THE MOVIE IRON MAN 3 DO YOU WANT TO BOOK ---");

System.out.println("\n\n");

System.out.println("ENTER: \n 1. for 8:00 am \n 2. for 11:00 am \n 3. for 2:00 pm \n 4. for 5:00 pm \n 5. for 9:00 pm"); try { c=Integer.parseInt(buf.readLine()); } catch(IOException e1) { System.out.println("invalid entry"); }

System.out.println("WHICH CLASS WOULD YOU LIKE TO BOOK:"); System.out.println("\n\n");

System.out.println(" 1.BUSSINESS\n 2.GOLD\n 3.SILVER\n 4.BRONZE"); try { type=Integer.parseInt(buf.readLine()); } catch(IOException e1) { System.out.println("invalid entry"); } switch(type) { case 1:

System.out.println("THE PRICE IS Rs.500 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); d=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+d*500); bill=bill+(d*500);

break; case 2:

System.out.println("THE PRICE IS Rs.250 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); d=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+d*250); bill=bill+(d*250);

break; case 3:

System.out.println("THE PRICE IS Rs.175 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); d=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+d*175); bill=bill+(d*175);

(40)

break; case 4:

System.out.println("THE PRICE IS Rs.100 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); d=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+d*100); bill=bill+(d*100); break; default: System.out.println("INVALID ENTRY"); } }

public static void FAF6()throws IOException {

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

System.out.println("--- WHAT TIMING OF THE MOVIE FAST AND FURIOUS 6 DO YOU WANT TO BOOK ---");

System.out.println("\n\n");

System.out.println("ENTER: \n 1. for 8:30 am \n 2. for 11:30 am \n 3. for 2:30 pm \n 4. for 5:30 pm \n 5. for 9:30 pm"); try { e=Integer.parseInt(buf.readLine()); } catch(IOException e1) { System.out.println("invalid entry"); }

System.out.println("WHICH CLASS WOULD YOU LIKE TO BOOK:"); System.out.println("\n\n");

System.out.println(" 1.BUSSINESS\n 2.GOLD\n 3.SILVER\n 4.BRONZE"); try { type1=Integer.parseInt(buf.readLine()); } catch(IOException e1) { System.out.println("invalid entry"); } switch(type1) { case 1:

System.out.println("THE PRICE IS Rs.500 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); f=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+f*500); bill=bill+(f*500);

break; case 2:

System.out.println("THE PRICE IS Rs.250 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); f=Integer.parseInt(buf.readLine());

(41)

System.out.println("THE AMT OF THE TICKETS= "+f*250); bill=bill+(f*250);

break; case 3:

System.out.println("THE PRICE IS Rs.175 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); f=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+f*175); bill=bill+(f*175);

break; case 4:

System.out.println("THE PRICE IS Rs.100 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); f=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+f*100); bill=bill+(f*100); break; default: System.out.println("INVALID ENTRY"); } }

public static void GGG()throws IOException {

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

System.out.println("--- WHAT TIMING OF THE MOVIE GO GOA GONE DO YOU WANT TO BOOK ---");

System.out.println("\n\n");

System.out.println("ENTER: \n 1. for 9:00 am \n 2. for 12:00 am \n 3. for 3:00 pm \n 4. for 6:00 pm \n 5. for 10:00 pm"); try { g=Integer.parseInt(buf.readLine()); } catch(IOException e1) { System.out.println("invalid entry"); }

System.out.println("WHICH CLASS WOULD YOU LIKE TO BOOK:"); System.out.println("\n\n");

System.out.println(" 1.BUSSINESS\n 2.GOLD\n 3.SILVER\n 4.BRONZE"); try { type2=Integer.parseInt(buf.readLine()); } catch(IOException e1) { System.out.println("invalid entry"); } switch(type2) { case 1:

System.out.println("THE PRICE IS Rs.500 PER TICKET"); System.out.println("\n\n");

(42)

System.out.println("ENTER THE NO. OF TICKETS"); h=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+h*500); bill=bill+(h*500);

break; case 2:

System.out.println("THE PRICE IS Rs.250 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); h=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+h*250); bill=bill+(h*250);

break; case 3:

System.out.println("THE PRICE IS Rs.175 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); h=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+h*175); bill=bill+(h*175);

break; case 4:

System.out.println("THE PRICE IS Rs.100 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); h=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+h*100); bill=bill+(h*100); break; default: System.out.println("INVALID ENTRY"); } }

public static void MOS()throws IOException {

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

System.out.println("--- WHAT TIMING OF THE MOVIE MAN OF STEEL DO YOU WANT TO BOOK ---");

System.out.println("\n\n");

System.out.println("ENTER: \n 1. for 9:30 am \n 2. for 12:30 am \n 3. for 3:30 pm \n 4. for 6:30 pm \n 5. for 10:30 pm"); try { i=Integer.parseInt(buf.readLine()); } catch(IOException e1) { System.out.println("invalid entry"); }

System.out.println("WHICH CLASS WOULD YOU LIKE TO BOOK:"); System.out.println("\n\n");

System.out.println(" 1.BUSSINESS\n 2.GOLD\n 3.SILVER\n 4.BRONZE"); try

{

(43)

} catch(IOException e1) { System.out.println("invalid entry"); } switch(type3) { case 1:

System.out.println("THE PRICE IS Rs.500 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); j=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+j*500); bill=bill+(j*500);

break; case 2:

System.out.println("THE PRICE IS Rs.250 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); j=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+j*250); bill=bill+(j*250);

break; case 3:

System.out.println("THE PRICE IS Rs.175 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); j=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+j*175); bill=bill+(j*175);

break; case 4:

System.out.println("THE PRICE IS Rs.100 PER TICKET"); System.out.println("\n\n");

System.out.println("ENTER THE NO. OF TICKETS"); j=Integer.parseInt(buf.readLine());

System.out.println("THE AMT OF THE TICKETS= "+j*100); bill=bill+(j*100); break; default: System.out.println("INVALID ENTRY"); } }

public static void SNACKS()throws IOException {

String n[]=new String[4]; n[0]="burger";

n[1]="nachos"; n[2]="coke"; n[3]="popcorn";

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

System.out.println("--- WHICH SNACK WOULD YOU LIKE TO BOOK ---"); System.out.println("\n\n");

(44)

System.out.println("ENTER THE NAME OF THE SNACK IN THE ABOVE MENTIONED ORDER,\nNOTE: AFTER WRITING THE NAME OF THE SSNACK HIT ENTER AND IF YOU DO NOT WANT TO BUY ANY SNACK THEN HIT ENTER AND TYPE THE NEXT SNACK");

try { s=buf.readLine(); } catch(NumberFormatException e1) { System.out.println("INVALID ENTRY"); } try { s1=buf.readLine(); } catch(NumberFormatException e1) { System.out.println("INVALID ENTRY"); } try { s2=buf.readLine(); } catch(NumberFormatException e1) { System.out.println("INVALID ENTRY"); } try { s3=buf.readLine(); } catch(NumberFormatException e1) { System.out.println("INVALID ENTRY"); } if(s.equalsIgnoreCase(n[0])) { System.out.println("\n\n"); System.out.println("FOR BURGER"); System.out.println("THE PRICE IS RS.80");

System.out.println("ENTER HOW MANY BURGERS DO YOU WANT TO BUY:"); try { quan=Integer.parseInt(buf.readLine()); } catch(IOException e2) { System.out.println("INVALID ENTRY"); } bill=bill+(quan*50); } if(s1.equalsIgnoreCase(n[1])) { System.out.println("\n\n"); System.out.println("FOR NACHOS");

(45)

System.out.println("THE PRICE IS RS.100");

System.out.println("ENTER HOW MANY NACHOS DO YOU WANT TO BUY:"); try { quan=Integer.parseInt(buf.readLine()); } catch(IOException e2) { System.out.println("INVALID ENTRY"); } bill=bill+(quan*100); } if(s2.equalsIgnoreCase(n[2])) { System.out.println("\n\n"); System.out.println("FOR COKE"); System.out.println("THE PRICE IS RS.70");

System.out.println("ENTER HOW MANY COKE DO YOU WANT TO BUY:"); try { quan=Integer.parseInt(buf.readLine()); } catch(IOException e2) { System.out.println("INVALID ENTRY"); } bill=bill+(quan*70); } if(s3.equalsIgnoreCase(n[3])) { System.out.println("\n\n"); System.out.println("FOR POPCORN"); System.out.println("THE PRIC IS RS.90");

System.out.println("ENTER HOW MANY POPCORN DO YOU WANT TO BUY:"); try { quan=Integer.parseInt(buf.readLine()); } catch(IOException e2) { System.out.println("INVALID ENTRY"); } bill=bill+(quan*90); } } }

(46)

Variable

Data type

Use of the variable

bill

Double

it stores the bill

amount

c

int

Stores the time

entered by the user

for the movie iron

man 3

type

Int

Stores the class of

the move iron man 3

d

Int

Stores the no. of

tickets bought for

movie iron man 3

flag

Int

Loop control variable

for checking the

snacks entered by

the use and

displaying them.

e

Int

Stores the time

entered by the user

for the movie fast

and the furious 6

type1

Int

Stores the class of

the move fast and

the furious 6

f

Int

Stores the no. of

tickets bought for

movie fast and the

(47)

furious 6

g

int

Stores the time

entered by the user

for the movie go goa

gone

type2

Int

Stores the class of

the move go goa

gone

h

Int

Stores the no. of

tickets bought for

movie go goa gone

i

int

Stores the time

entered by the user

for the movie man of

steel

type3

Int

Stores the class of

the move man of

steel

j

Int

Stores the no. of

tickets bought for

movie man of steel

quan

Int

Stores the quantity

of snacks bought by

the user

n[]

String(array)

Stores the snacks

options for the user

References

Related documents

One should be able to run the scanner on a file of Java source code by typing in the command... scanner f ...where f is the name of the Java file to

Hence we have character stream that java is one last modified time i have a file path may writting to a file java program receives data..

The wellbore characteristics affecting completion con- figuration or component selection are best summarized by reviewing the drilling, evaluation and pre-completion activities

• How can tell when there are no more characters left to read from the input file associated with a particular file stream.. o You need to detect the &#34;end of

As such, it is common to divide the territory into coastal and interior regions when performing data analysis (Fig. 2 shows the Portuguese population per district and the

Argentina, Bolivia, Brazil, Colom- bia, Costa Rica, Cuba, Guatemala, Mexico, Panama, Paraguay, Peru, Puerto Rico, Surinam, Trinidad, and Venezuela.. Megistopoda

Although they work in a care reality in which all possible measures are taken to avoid lack of supplies and not to impair the quality of intensive care, nursing care

load(InputStream stream) loadFromURL(URL url) load(InputStream stream) parseLocation(String line) parseTime(String line) parseTemperature (String line).