[go: up one dir, main page]

0% found this document useful (0 votes)
7 views27 pages

Week10 L1 Arrays

The document provides an overview of arrays in Java, explaining their declaration, initialization, and usage. It includes examples of basic array operations, such as filling an array, modifying values, and printing elements, as well as common pitfalls like ArrayIndexOutOfBoundsException. Additionally, it presents sample Java programs demonstrating array manipulation and counting characters in strings.

Uploaded by

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

Week10 L1 Arrays

The document provides an overview of arrays in Java, explaining their declaration, initialization, and usage. It includes examples of basic array operations, such as filling an array, modifying values, and printing elements, as well as common pitfalls like ArrayIndexOutOfBoundsException. Additionally, it presents sample Java programs demonstrating array manipulation and counting characters in strings.

Uploaded by

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

By

Dr. Yasser Abdelhamid


 Arrays
 http://www.javatpoint.com/
 Pearson Education, Inc. slides

Dr. Yasser Abdelhamid


 An array is a collection of elements of
similar type stored in contiguous memory
locations.
 The element type can be a primitive data
type or an object reference.
 int [] marks = new int[5];
 Based on the following array, what is the
value for each statement?
 a. height[1]
 b. height[2] + height[5]
 c. height[2 + 5]
 d. the value stored at index 8
 e. the fourth value
 f. height.length
 InJava, the array itself is an object that must
be instantiated
 Another way to depict the scores array:

scores 79
87
94
82
The name of the array 67
is an object reference 98
variable 87
81
74
91
 The scores array could be declared as
follows:
int[] scores = new int[10];

 Thetype of the variable scores is int[] (an


array of integers)
 Note that the array type does not specify its
size, but each object of that type has a
specific size.
 The
reference variable scores is set to a
new array object that can hold 10 integers
 Some other examples of array
declarations:

int[] weights = new int[2000];


double[] prices = new double[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
 The for-each version of the for loop can be
used when processing array elements:
for (int score : scores)
System.out.println(score);

 Thisis only appropriate when processing all


array elements starting at index 0

 It can't be used to set the array values


//********************************************************************
// BasicArray.java Author: Lewis/Loftus
//
// Demonstrates basic array declaration and use.
//********************************************************************

public class BasicArray


{
//-----------------------------------------------------------------
// Creates an array, fills it with various integer values,
// modifies one value, then prints them out.
//-----------------------------------------------------------------
public static void main(String[] args)
{
final int LIMIT = 15, MULTIPLE = 10;

int[] list = new int[LIMIT];

// Initialize the array values


for (int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

// Print the array values


for (int value : list)
System.out.print(value + " ");
}
}
//********************************************************************
Output
// BasicArray.java Author: Lewis/Loftus
//
// 10
0 Demonstrates
20 30 basic
40 999array60declaration
70 80 and90 use.
100 110 120 130 140
//********************************************************************

public class BasicArray


{
//-----------------------------------------------------------------
// Creates an array, fills it with various integer values,
// modifies one value, then prints them out.
//-----------------------------------------------------------------
public static void main(String[] args)
{
final int LIMIT = 15, MULTIPLE = 10;

int[] list = new int[LIMIT];

// Initialize the array values


for (int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

// Print the array values


for (int value : list)
System.out.print(value + " ");
}
}
Write an array declaration to represent the
ages of 100 children.

Write code that prints each value in an array of


integers named values.
Write an array declaration to represent the
ages of 100 children.

int[] ages = new int[100];

Write code that prints each value in an array of


integers named values.

for (int value : values)


System.out.println(value);
 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 range 0 to N-1
 The Java interpreter throws an
ArrayIndexOutOfBoundsException if an array
index is out of bounds
 This is called automatic bounds checking
 For example, if the array codes can hold 100
values, it can be indexed from 0 to 99
 If the value of count is 100, then the following
reference will cause an exception to be thrown:
System.out.println(codes[count]);

 It’s common to introduce off-by-one errors when


using arrays:

problem

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


codes[index] = index*50 + epsilon;
 Each array object has a public constant
called length that stores the size of the
array
 It is referenced using the array name:
scores.length

 Notethat length holds the number of


elements, not the largest index
 See ReverseOrder.java
 See LetterCount.java

Copyright © 2014 Pearson Education, Inc.


//********************************************************************
// ReverseOrder.java Author: Lewis/Loftus
//
// Demonstrates array index processing.
//********************************************************************

import java.util.Scanner;

public class ReverseOrder


{
//-----------------------------------------------------------------
// Reads a list of numbers from the user, storing them in an
// array, then prints them in the opposite order.
//-----------------------------------------------------------------
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);

double[] numbers = new double[10];

System.out.println("The size of the array: " + numbers.length);

// continue next page

Copyright © 2014 Pearson Education, Inc.


for (int index = 0; index < numbers.length; index++)
{
System.out.print("Enter number " + (index+1) + ": ");
numbers[index] = scan.nextDouble();
}

System.out.println("The numbers in reverse order:");

for (int index = numbers.length-1; index >= 0; index--)


System.out.print(numbers[index] + " ");
}
}

Copyright © 2014 Pearson Education, Inc.


Sample Run
The size of the array: 10
Enter number 1: 18.36
Enter number 2: 48.9
Enter number 3: 53.5
Enter number 4: 29.06
Enter number 5: 72.404
Enter number 6: 34.8
Enter number 7: 63.41
Enter number 8: 45.55
Enter number 9: 69.0
Enter number 10: 99.18
The numbers in reverse order:
99.18 69.0 45.55 63.41 34.8 72.404 29.06 53.5 48.9
18.36

Copyright © 2014 Pearson Education, Inc.


//********************************************************************
// LetterCount.java Author: Lewis/Loftus
//
// Demonstrates the relationship between arrays and strings.
//********************************************************************

import java.util.Scanner;

public class LetterCount


{
//-----------------------------------------------------------------
// Reads a sentence from the user and counts the number of
// uppercase and lowercase letters contained in it.
//-----------------------------------------------------------------
public static void main(String[] args)
{
final int NUMCHARS = 26;

Scanner scan = new Scanner(System.in);

int[] upper = new int[NUMCHARS];


int[] lower = new int[NUMCHARS];

char current; // the current character being processed


int other = 0; // counter for non-alphabetics

// continue next page

Copyright © 2014 Pearson Education, Inc.


// Read a line
System.out.println("Enter a sentence:");
String line = scan.nextLine();

// Count the number of each letter occurence


for (int ch = 0; ch < line.length(); ch++)
{
current = line.charAt(ch);
if (current >= 'A' && current <= 'Z')
upper[current-'A']++;
else
if (current >= 'a' && current <= 'z')
lower[current-'a']++;
else
other++;
}

// continue next page

Copyright © 2014 Pearson Education, Inc.


// Print the results
System.out.println();
for (int letter=0; letter < upper.length; letter++)
{
System.out.print( (char) (letter + 'A') );
System.out.print(": " + upper[letter]);
System.out.print("\t\t" + (char) (letter + 'a') );
System.out.println(": " + lower[letter]);
}

System.out.println();
System.out.println("Non-alphabetic characters: " + other);
}
}

Copyright © 2014 Pearson Education, Inc.


Sample Run
Enter a sentence:
In Casablanca, Humphrey Bogart never says "Play it again, Sam."

A: 0 a: 10
B: 1 b: 1
C: 1 c: 1
D: 0 d: 0
E: 0 e: 3
F: 0 f: 0
G: 0 g: 2 Sample Run (continued)
H: 1 h: 1
I: 1 i: 2 R: 0 r: 3
J: 0 j: 0 S: 1 s: 3
K: 0 k: 0 T: 0 t: 2
L: 0 l: 2 U: 0 u: 1
M: 0 m: 2 V: 0 v: 1
N: 0 n: 4 W: 0 w: 0
O: 0 o: 1 X: 0 x: 0
P: 1 p: 1 Y: 0 y: 3
Q: 0 q: 0 Z: 0 z: 0

continue Non-alphabetic characters: 14

Copyright © 2014 Pearson Education, Inc.


1. Write a Java program that accepts an array of
integers and returns the sum of all the even
numbers in the array. For example, if the input
array is {1, 2, 3, 4, 5, 6}, the program should
return 12 (which is the sum of 2, 4, and 6).
2. Write a Java program that accepts an array of
strings and returns the length of the longest
string in the array. For example, if the input
array is {"cat", "dog", "elephant", "bird"}, the
program should return 8 (which is the length of
"elephant").
3. Write a Java program that accepts two arrays of
integers and returns a new array that contains
only the common elements between the two
arrays. For example, if the first array is {1, 2, 3,
4, 5} and the second array is {3, 4, 5, 6, 7}, the
program should return an array with {3, 4, 5}.

You might also like