[go: up one dir, main page]

0% found this document useful (0 votes)
4 views33 pages

Lecture07 Arrays and Exceptions

The document provides an overview of fundamental concepts in Java programming, focusing on arrays and exceptions. It explains how to declare and use arrays, including initializer lists and methods for passing arrays, as well as how to handle exceptions like NumberFormatException. The lecture concludes with practical exercises and outcomes related to these topics.

Uploaded by

maureen kakoma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views33 pages

Lecture07 Arrays and Exceptions

The document provides an overview of fundamental concepts in Java programming, focusing on arrays and exceptions. It explains how to declare and use arrays, including initializer lists and methods for passing arrays, as well as how to handle exceptions like NumberFormatException. The lecture concludes with practical exercises and outcomes related to these topics.

Uploaded by

maureen kakoma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Computer

Programming
Arrays and exceptions

It is a capital mistake to theorise before one has the data


Sherlock
Holmes
Lecture
objectives
To be able to understand the following fundamental concepts
of the Java programming language:

• Arrays
• Exceptions
Array
• s programming construct
An array is a simple but powerful
• Consider this cumbersome expression

avgSales = (janSales + febSales + marSales + aprSales


+ maySales + junSales + julSales + augSales +
sepSales + octSales + novSales + decSales) /12;

• If the type of each field is identical we can create an


array
or list of values
• Instead of defining 12 variables, we define one and access it
with an index
Array
• s
An array is an ordered list of values
The entire array Each value has a numeric index
has a single name

0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91

This array holds 10 values that are indexed from 0 to


9
Array
• s is referenced using the array
A particular value in an array
name followed by the index in square brackets
• For example, the expression

scores[2]

refers to the value 94 (which is the 3rd value in the array)


0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91
Array
• s
An array stores multiple values of the same type
• That type can be primitive types or objects
• Therefore, we can create
– an array of integers
– an array of doubles
– an array of characters, or
– an array of String objects etc.
• In Java, the array itself is an object
Declaring
• The scores Arrays
array could be declared in either of
the following ways:

int[ ] scores = new int[10];


or
int scores [ ] = new int[10];

• The type of the variable scores is int[]


– (an array of integers)
//-----------------------------------------------------------------
// Creates an array, fills it, modifies one value, then
//-----------------------------------------------------------------
prints them out.

public class BasicArray


{
public static void main (String[] args)
{
int[ ] list = new int [3];

for (int index = 0; index < 3; index++)


list[index] = index * 10;

list[1] = 999; // change one

array value for (int index = 0; index < 3;

index++)
System.out.print (list[index] + " ");
0 }10 20 0 999 20
}
Practic
• e
Create an array that hold 5 integers
• Write a For loop to loop 5 times, each time prompting the
user to enter an integer
• Store each integer in the array

• Now create another For loop ( the same)


• Access each value in the array, print them and total them
• Print the total
public class AddNumbers Enter an
{ integer: 10
public static void main Enter an
(String[] args) integer: 20
{
Enter an
int total = 0;
int[ ] numbers = integer: 30
new int[5]; String Enter an
inputNum; integer: 40
for (int index = 0; index < 5; Enter an
index++)
{ integer: 50 10
inputNum 20
=JOptionPane.showInp 30
utDialog ("Enter an 40
integer: "); 50
numbers[index]
for (int index == 0; index < 5; index++) total = 150
{ Integer.parseInt(inputNum);
} System.out.println(numbers[index]);
total = total + numbers[index];
}
JOptionPane.showMessageDialog (null, “total =
“ + total);
}
}
Bounds
• Checking
Once an array is created, it has a fixed size
• An index used in an array reference must specify a valid
element
• That is, the index value must be in bounds (0 to n-1)
• The Java interpreter will throw an exception if an array
index is out of bounds
Bounds
• Each array objectChecking
has a public constant called length
that stores the size of the array ie the number of elements

• It is referenced using the array name (just like any other


object):

scores.length
public class ReverseNumbers
Array size = 3
{
Enter number 1:
public static void main 1
(String[] args)
Enter number 2:
{ 2
double[] numbers = new Enter number 3:
double[3 ]; String 3
inputNum;
System.out.println (“Array size = " + The numbers in
numbers.length); reverse: 3.0 2.0
for (int index = 0; index < numbers.length; 1.0
index++)
{
inputNum
=JOptionPane.showInputDi
alog ("Enter number " +
(index+1) + ": ");
numbers[index] =
Double.parseDouble(inputNum);
}

System.out.println ("The numbers in


reverse:");
Initializer
• Lists
An initializer list can be used to instantiate and initialize an
array in one step
• Values are delimited by braces and separated by commas

• Examples:

int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114};

char[ ] letterGrades = {'A', 'B', 'C', 'D', 'F'};


Initializer
• Lists
Note that when an initializer list is used:
– the new operator is not used
– no size value is specified

• The size of the array is determined by the number of items


//
****************************************************
*********
// GradeRange.java
// Demonstrates the use of an array of String
objects.
//
****************************************************
**********

public class GradeRange


{
public static void main (String[] args)
{
String[] grades = {“HD", “D", “CR", “P“,
} “N”};
} HD 8
0
int[] cutoff = {80, 70, 60, 50, 0};
D 7
0
for (int level = 0; level < cutoff.length;
CR 6
level++) System.out.println (grades[level]
0
+ "\t" + cutoff[level]);
Passing Array elements to
Methods
• You can pass a single array element to a method in
exactly the same way as you pass a variable

• The variables are local to the method and any changes to


variables passed into methods are not permanent
– ie changes are not reflected in the main() program
public class PassArrayElement
In main
{
method 5 In
public static void main (String [ ] args)
{ main method
int [ ] nums = {5, 10, 15}; 10 In main
for (int index = 0; index < nums.length; method 15
index++) In
System.out.println(“In main method “ + methodGetOn
for nums[index]);
(int index = 0; index < eInteger 5
nums.length; index++) After change
methodGetOneInteger(nums[ index]) 999
for ;(int index = 0; index < nums.length; index++) In
System.out.println(“At end of main method “ + methodGetOn
} nums[index]); eInteger 10
After change
public static void methodGetOneInteger (int 999
num) In
{ methodGetOn
System.out.println(“In eInteger 15
methodGetOneInteger “ + num); num After change
= 999; 999
System.out.println(“After change “ + At end of main
num); method 5 At end
Passing Arrays to
• Methods
Arrays are objects
• Arrays are passed by reference
– the method receives the memory address of the array and
has access to the actual values in the array elements
– the method can therefore change values in the array
public class PassArray
In main
{
method 5 In
public static void main (String [ ] args)
{ main method
int [ ] nums = {5, 10, 15}; 10 In main
for (int index = 0; index < nums.length; method 15
index++) In
System.out.println(“In main method “ + methodGetsAr
nums[index]);
methodGetsArray(nu ray 5
ms); In
for (int index = 0; index < nums.length; index++) methodGetsAr
System.out.println(“At end of main method “ + ray 10
} nums[index]); In
methodGetsArr
public static void methodGetsArray (int [ ] numsArray) ay 15
{ At end of main
for (int index = 0; index < numsArray.length; index+ method 999 At end
+) of main method
{ 999 At end of main
System.out.println(“In methodGetsArray “ + method 999
numsArray [index]); numsArray[index] = 999;
}
}
Pseudocod
• Creating an array e
create numbers array as new int [size]

• Using an array
– Very similar to java code

total = total + numbers [index]


Exception
s
• When a Java program performs an illegal operation,
– an exception happens
• Exceptions occur during program execution – not
compilation ie errors the compiler cannot detect
• If a program has no special provisions for dealing with
exceptions, it will behave badly if one occurs
– the program will terminate immediately
• Java provides a way for a program to detect that an
exception has occurred and execute statements that are
designed to deal with the problem.
Handling
• Exceptions
When an exception occurs (is thrown), the program has the
option of catching it.
• In order to catch an exception, the code in which the
exception might occur must be enclosed in a try
block.
• After the try block comes a catch block that catches
the exception (if it occurs) and performs the desired
action.

• There are various exceptions defined in java


• We are only learning NumberFormatException in this unit
Handling
try Exceptions
{
// one or more statements at least one of which may
// be capable of causing an exception
}
catch (exceptionName argument)
{
// one or more statements to execute if the exception occurs
}

• If an exception is thrown within the try block, and the


exception matches the one named in the catch block,
the code in the catch block is executed
• If the try block executes normally—without an
exception—the catch block is
NumberFormatException
• NumberFormatException
– Occurs when an attempt is made to convert a string that does
not contain the appropriate characters
– eg trying to convert alpha characters or spaces to an integer

try
{
int num = Integer.parseInt(“doh”);
}

catch (NumberFormatException e)
{
System.out.println("Error: Not an
integer");
}
Valid data
• entry
A robust program will not allow erroneous data input by a
user to cause it to crash
– If invalid data is entered it needs to be caught

• Put the try and catch blocks in a loop


– This allows the user multiple attempts to enter a valid data
Practic
• Write a do while loop that
e
– prompts a user to enter an integer between 1 and 10 inclusive
– Repeats the prompt while the number is not in that range
– Leave out exception handling
String
numStr;
int num =
0; do
{
numStr = JOptionPane.showInputDialog ("Enter an integer
between 1 and 10"); num = Integer.parseInt(numStr);
}
while (num < 1 || num > 10);

• Now use a try/ catch block to catch a


NumberFormatException
A
String solution
numStr;
int num =
0;

do
{
numStr
=
JOption
Pane.sh
owInpu
tDialog
("Enter
an
integer
whilebetwee
(num < 1 ||
Sentinels of
• Flags
Another name for a sentinel variable used for an event
controlled loop is a “flag”
• A flag indicates something of interest for program
control
• In exceptions if there is no valid number or range of
numbers – you can use a boolean variable to flag a valid or
invalid state
while (invalidNumber)
this is of course equivalent to and better programming style than:
while (invalidNumber == true)
boolean invalidNumber = true;
do
{
String userInputStr = JOptionPane.showInputDialog
("Enter an integer: ");

try
{
userInput =
Integer.parseInt(userInputStr);
invalidNumber = false;
}

catch (NumberFormatException e)
{
JOptionPane.showMessageDialog
(null, “That is not an integer");
Pseudocod
• e with indentation and END etc as
Show try and catch blocks
with loops and decisions
• Naming the end eg ENDTRY etc is only useful if there are
many lines of code in between

DO
numStr  prompt user to "Enter an integer
between 1 and 10" TRY
num = Integer.parseInt(numStr);
END
CATCH
(NumberFormatExcepti
on) display error
messge
END
WHILE (num < 1 OR num >
10)
Lecture
Outcomes
Today we have covered:
– arrays
– initializer lists
– passing individual array elements to methods
– passing arrays to methods
– exceptions

• Questions?

You might also like