Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

CHAPTER 5

ARRAYS

5.1 Introducing Arrays

Array is a data structure that represents a collection of the same types of data as
shown in Figure 5.1.

double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5

Array reference myList[2] 3.3


variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

myList[7] 45.45

myList[8] 99.993

myList[9] 11123

Figure 5.1 The array myList has ten elements of double type and int
indices from 0 to 9.

5.2 Declaring Array Variables and Creating Arrays


To use an array in a program, you must declare a variable to reference the array
and specify the type of array the variable can reference. Here is the syntax for
declaring an array variable:
datatype[] arrayRefVar;or
datatype arrayRefVar[]; /* This style is correct, but not preferred
*/
Example:
double[] myList; or
double myList[];
An array variable contains a reference to an array. If a variable does not reference
to an array, the value of the variable is null.
Creating Arrays
You can create an array by using the new operator with the following syntax:
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
Declaring an array variables, creating an array, and assigning the reference of the
array to the variable can be combined in one statement, as follows:
datatype[] arrayRefVar = new datatype[arraySize];
or
datatype arrayRefVar[] = new datatype[arraySize];
Example:
double[] myList = new double[10];
double myList[] = new double[10];
For simplicity, we always say that, myList is an array, instead stating that
myList is a variable that contains a reference to an array.

5.2.1 The Length of an Array


Once an array is created, its size is fixed. It cannot be changed. You can find its
size using
arrayRefVar.length
For example,
myList.length returns 10
5.2.2 Default Values
When an array is created, its elements are assigned the default value of
0 for the numeric primitive data types,
'\u0000' for char types, and
false for boolean types.
0 int
0.0 double
null string, array, object ➔ class

5.2.3 Indexed Variables


The array elements are accessed through the index. The array indices are 0-based,
i.e., it starts from 0 to arrayRefVar.length-1. In the example in Figure 5.1,
myList holds ten double values and the indices are from 0 to 9. Each element in
the array is represented using the following syntax, known as an indexed variable:
arrayRefVar[index];
Using Indexed Variables
After an array is created, an indexed variable can be used in the same way as a
regular variable. For example, the following code adds the value in
myList[0]andmyList[1]tomyList[2].

myList[2] = myList[0] + myList[1];

for example, the following loop:


for (int i = 0; i < myList.length; i++)
myList[i] = i;
In this example, myList.length returns the array size (10) for myList.

5.3 Initializing and Processing Arrays


Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one statement. This shorthand notation is
equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

Caution
Using the shorthand notation, you have to declare, create, and initialize the array
all in one statement. Splitting it would cause a syntax error. For example, the
following is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
You can also create and initialize an array using the following syntax:
new dataType[]{literal0, literal1, …,literalk};
For example,
double[] myList = {1, 2, 3};
// sometimes later …
myList = new double[]{1.9, 2.9, 3.4, 3.5}
When processing array elements, you will often use a for loop. Here are the
reasons:
• All of the elements in an array are of the same type.
• Since the size of the array is known, it is natural to use a for loop.
Enhanced forLoop
JDK 1.5 introduced a new for loop that enables you to traverse the complete array
sequentially without using an index variable. For example, the following code
displays all elements in the array myList:
for (double value: myList)
System.out.println(value);
In general, the syntax is
for (elementType value: arrayRefVar) {
// Process the value
}
You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.
Example 5.1: Testing Arrays
Problem
Write a program that receives 6 numbers from the keyboard, finds the largest
number and counts the occurrence of the largest number entered from the
keyboard. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its
occurrence count is 4.
Solution
The source code for the program is shown below:
import javax.swing.JOptionPane;

public class TestArray {


/** Main method */
public static void main(String[] args) {
final int TOTAL_NUMBERS = 6;
int[] numbers = new int[TOTAL_NUMBERS];

// Read all numbers


for (int i = 0; i < numbers.length; i++) {
String numString =
JOptionPane.showInputDialog(null,"Enter a number:",
"Example 5.1 Input",
JOptionPane.QUESTION_MESSAGE);

// Convert string into integer


numbers[i] = Integer.parseInt(numString);
}

// Find the largest


int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (max < numbers[i])
max = numbers[i];
}

// Find the occurrence of the largest number


int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == max) count++;
}

// Prepare the result


String output = "The array is ";
for (int i = 0; i < numbers.length; i++) {
output += numbers[i] + " ";
}

output += "\nThe largest number is " + max;


output += "\nThe occurrence count of the largest
number "
+ "is " + count;

// Display the result


JOptionPane.showMessageDialog(null, output,
"Example 5.1 Output",
JOptionPane.INFORMATION_MESSAGE);
}
}

Figure 5.1 shows the output of example 5.1.


Figure 5.1 The output of example 5.1

You can trace the value of array elements in the debugger as shown in Figure 5.2.
Example 5.2 Assigning Grades
Problem
Write a program to read student scores (int), get the best score, and then assign
grades based on the following scheme:
• Grade is A if score is >= best–10;
• Grade is B if score is >= best–20;
• Grade is C if score is >= best–30;
• Grade is D if score is >= best–40;
• Grade is F otherwise.
The following code gives the solution to the problem. The output of a sample run
of the program is shown in Figure 5.3.
The Program:
import javax.swing.JOptionPane;

public class AssignGrade {


/** Main method */
public static void main(String[] args) {
int numberOfStudents = 0; // The number of students
int[] scores; // Array scores
int best = 0; // The best score
char grade; // The grade
// Get number of students
String numberOfStudentsString =
JOptionPane.showInputDialog(
null, "Please enter number of students:",
"Example 5.2 Input",
JOptionPane.QUESTION_MESSAGE);

// Convert string into integer


numberOfStudents =
Integer.parseInt(numberOfStudentsString);
Array
// Create array scores
scores = newint[numberOfStudents];

// Read scores and find the best score


for (int i = 0; i < scores.length; i++) {
String scoreString =
JOptionPane.showInputDialog(null,
"Please enter a score:",
"Example 5.2 Input",
JOptionPane.QUESTION_MESSAGE);

// Convert string into integer


scores[i] = Integer.parseInt(scoreString);
if (scores[i] > best)
best = scores[i];
}

// Declare and initialize output string


String output = "";

// Assign and display grades


for (int i = 0; i < scores.length; i++) {
if (scores[i] >= best - 10)
grade = 'A';
elseif (scores[i] >= best - 20)
grade = 'B';
elseif (scores[i] >= best - 30)
grade = 'C';
elseif (scores[i] >= best - 40)
grade = 'D';
else
grade = 'F';
output += "Student " + i + " score is " +
scores[i] + " and grade is " + grade + "\n";
}

// Display the result


JOptionPane.showMessageDialog(null, output,
"Example 5.2 Output",
JOptionPane.INFORMATION_MESSAGE);
}
}
The output:

Figure 5.3 Input and output of example 5.2

5.5 Copying Arrays


Often, in a program, you need to duplicate an array or a part of an array. In such
cases you could attempt to use the assignment statement (=), as follows:
list2 = list1;
Before the assignment After the assignment
list2 = list1; list2 = list1;

list1 list1
Contents Contents
of list1 of list1

list2 list2
Contents Contents
of list2 of list2
Garbage

Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[]targetArray = new int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++)


targetArray[i] = sourceArray[i];
The arraycopy Utility
arraycopy(sourceArray, src_pos, targetArray, tar_pos,
length);
Example:
System.arraycopy(sourceArray, 0, targetArray, 0,
sourceArray.length);

5.6 Passing Arrays to Methods


Just as you can pass the parameters of primitive types to methods, you can also
pass the parameters of array types to methods. The next example passes the array
list as an argument to the method printArray.
Example:
public class TestPassingArray {
public static void main(String[] args) {
int[] list = {1, 3, 5, 7, 9, 11, 13};
printArray(list);
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
For a parameter of an array type, the value of the parameter contains a reference
to an array; this reference is passed to the method. Any changes to the array that
occur inside the method body will affect the original array that was passed as the
argument.
Invoke the method
int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
Invoke the method
printArray(new int[]{3, 1, 2, 6, 4, 2});
5.6.1 Anonymous Array Anonymous array

The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array. Such array is called an
anonymous array.
5.6.2 Pass By Value
Java uses pass by value to pass parameters to a method. There are important
differences between passing a value of variables of primitive data types and
passing arrays.
• For a parameter of a primitive type value, the actual value is passed. Changing the
value of the local parameter inside the method does not affect the value of the
variable outside the method.
• For a parameter of an array type, the value of the parameter contains a reference
to an array; this reference is passed to the method. Any changes to the array that
occur inside the method body will affect the original array that was passed as the
argument.
Simple Example
public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; /* y represents an array of
int values */

m(x, y); // Invoke m with arguments x and y

System.out.println("x is " + x);//x is 1


System.out.println("y[0] is " + y[0]);// y[0]is
5555
}

public static void m(int number, int[] numbers) {


number = 1001; /* Assign a new value to number */
numbers[0] = 5555; /* Assign a new value to
numbers[0] */
}
}
5.6.3 Call Stack
Stack Heap
Space required for
method m
int[] numbers:reference
The arrays are
int number: 1 Array of stored in a
ten int heap.
Space required for the values is
main method stored here
int[] y: reference
int x: 1

When invoking m(x, y), the values of x and y are passed to number and numbers.
Since y contains the reference value to the array, numbers now contains the same
reference value to the same array.

5.6.4 Heap
The JVM stores the array in an area of memory, called heap, which is used for
dynamic memory allocation where blocks of memory are allocated and freed in
an arbitrary order.

Example 5.3 Passing Arrays as Arguments


Demonstrate differences of passing primitive data type variables and array
variables.
Problem:
Write two methods for swapping elements in an array. The first method, named
swap, attempts to swap two int arguments. The second method, named
swapFirstTwoInArray, attempts to swap the first two elements in the array
argument.
Solution:
The program
public class TestPassArray {
/** Main method */
public static void main(String[] args) {
int[] a = {1, 2};

// Swap elements using the swap method


System.out.println("Before invoking swap");
System.out.println("array is {" + a[0] + ", " +
a[1] + "}");
swap(a[0], a[1]);
System.out.println("After invoking swap");
System.out.println("array is {" + a[0] + ", " +
a[1] + "}");

// Swap elements using the swapFirstTwoInArray


method
System.out.println("Before invoking
swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " +
a[1] + "}");
swapFirstTwoInArray(a);
System.out.println("After invoking
swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " +
a[1] + "}");
}

/** Swap two variables */


public static void swap(int n1, int n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}

/** Swap the first two elements in the array */


public static void swapFirstTwoInArray(int[] array) {
int temp = array[0];
array[0] = array[1];
array[1] = temp;
}
}
The output:

Figure 5.4 Output of example 5.3


Stack Heap Stack
Space required for the
Space required for the swapFirstTwoInArray
swap method method
n2: 2 int[] array reference
n1: 1

Space required for the Space required for the


main method main method
int[] a reference int[] a reference
a[1]: 2
a[0]: 1
Invoke swap(int n1, int n2). Invoke swapFirstTwoInArray(int[] array).
The primitive type values in The arrays are The reference value in a is passed to the
a[0] and a[1] are passed to the stored in a swapFirstTwoInArray method.
swap method. heap.

Returning an Array from a Method


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Example 5.5 Counting Occurrence of Each Letter
A method may return an array, as shown in the following example.
(A) Executing (B) After exiting
createArray in Line 6 createArray in Line 6

Stack Heap Stack Heap

Space required for the


Array of 100 Array of 100
createArray method
characters characters
char[] chars: ref
Space required for the Space required for the
main method main method
char[] chars: ref char[] chars: ref

Problem:
Write a program that does the following:
1. Generate 100 lowercase letters randomly and assign them to an array of
characters.
2. Count the occurrence of each letter in the array.
The program:
public class CountLettersInArray {
/** Main method */
public static void main(String args[]) {
// Declare and create an array
char[] chars = createArray();

// Display the array


System.out.println("The lowercase letters are:");
displayArray(chars);

// Count the occurrences of each letter


int[] counts = countLetters(chars);

// Display counts
System.out.println();
System.out.println("The occurrences of each letter
are:");
displayCounts(counts);
}

/** Create an array of characters */


public static char[] createArray() {
// Declare an array of characters and create it
char[] chars = new char[100];

// Create lowercase letters randomly and assign


// them to the array
for (int i = 0; i < chars.length; i++)
chars[i] =
RandomCharacter.getRandomLowerCaseLetter();

// Return the array


return chars;
}

/** Display the array of characters */


public static void displayArray(char[] chars) {
// Display the characters in the array 20 on each
line
for (int i = 0; i < chars.length; i++) {
if ((i + 1) % 20 == 0)
System.out.println(chars[i] + " ");
else
System.out.print(chars[i] + " ");
}
}

/** Count the occurrences of each letter */


public static int[] countLetters(char[] chars) {
// Declare and create an array of 26 int
int[] counts = new int[26];

// For each lowercase letter in the array, count


it
for (int i = 0; i < chars.length; i++)
counts[chars[i] - 'a']++;

return counts;
}

/** Display counts */


public static void displayCounts(int[] counts) {
for (int i = 0; i < counts.length; i++) {
if ((i + 1) % 10 == 0)
System.out.println(counts[i] + " " + (char)(i
+ 'a'));
else
System.out.print(counts[i] + " " + (char)(i +
'a') + " ");
}
}
}
The output:

Figure 5.6 Output of example 5.5


5.9 Multidimensional Arrays
You have used one-dimensional arrays to model linear collections of elements. To
represent a matrix or a table, it is necessary to use a two-dimensional array.
Occasionally, you will need to represent n-dimensional data structures. In Java,
you can create n-dimensional arrays for any integer n, as long as your computer
has sufficient memory to store the array.
5.9.1 Declaring Variables of Multidimensional Arrays and Creating
Multidimensional Arrays

In Java, a two-dimensional array is declared as an array of arrays. Here is the


syntax
// Declare array ref var
dataType[][] refVar;
or
dataType refVar[][];

You can create a two-dimensional array of 10 by 10 int values and assign its
reference to variable as follows:
/* Create array and assign its reference to variable */
refVar = new dataType[10][10];
/* Combine declaration and creation in one statement */
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];

Examples: Declaring Variables of Two-dimensional Arrays and Creating


Two-dimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);
double[][] x;
5.9.2 Two-dimensional Array Illustration
Two subscripts are used in a two-dimensional array, one for the row, and the other
for the column. As in a one-dimensional array, the index for each subscript is of
the int type and starts from 0, as shown in Figure 5.11
0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3

1 1 1 4 5 6

2 2 7 2 7 8 9

3 3 3 10 11 12

4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; {4, 5, 6},
matrix[2][1] = 7; {7, 8, 9},
{10, 11, 12}
matrix.length? 5 };
matrix[0].length? 5 array.length? 4
array[0].length? 3

Figure 5.11 The index of each subscript of a multidimensional array is an int


value starting from 0.

5.9.3 Declaring, Creating, and Initializing Using Shorthand Notations


You can also use an array initializer to declare, create and initialize a two-
dimensional array. For example,
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
this is equivalent to the following statements.
int[][] array = new int[4][3];
array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
Similarly, the following syntax declares a three-dimensional array variable scores,
creates an array, and assigns its reference to scores.
double[][][] scores = new double[10][5][2];

5.9.4 Lengths of Two-dimensional Arrays


int[][] x = new int[3][4];
x
x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4
x[0]
x[1] x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4

x[2]
x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4
x.length is 3

5.9.5 Ragged Arrays


Each row in a two-dimensional array is itself an array. So, the rows can have
different lengths. Such an array is known as a ragged array. For example
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};

matrix.length is 5
matrix[0].length is 5
matrix[1].length is 4
matrix[2].length is 3
matrix[3].length is 2
matrix[4].length is 1

int[][] triangleArray = { 1 2 3 4 5
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, 1 2 3 4
{3, 4, 5},
{4, 5}, 1 2 3
{5}
}; 1 2

1 2

If you don't know the values in a ragged array in advance, you can create a ragged
array using the syntax that follows:
int[][] triangleArray = new int[5][];
triangleArray[0] = new int[5];
triangleArray[1] = new int[4];
triangleArray[2] = new int[3];
triangleArray[3] = new int[2];
triangleArray[4] = new int[1];
int x[][]={{1,2,3},{1,2},{1}};
sum(x);
public static int sum(int[][]x){
int sum=0;
for(int i=0;i<x.length;i++)
for(int j=0;j<x[0].length;j++)
sum+=x[i][j];
return sum;
}
Example 5.10 Adding and multiplying two Matrices
Problem:
Write a program that uses two-dimensional arrays to represent two matrices. The
program then adds and multiplies the two matrices.
Solution:
Assume both arrays are 5 by 5 with int type elements. The program is given below.
The output of the program is shown in Figure 5.12.
The program:
// TestMatrixOperation.java add and multiply two
matrices
public class TestMatrixOperation {
/** Main method */
public static void main(String[] args) {
// Create two matrices as two dimensional arrays
int[][] matrix1 = new int[5][5];
int[][] matrix2 = new int[5][5];
// assign random values to matrix1 and matrix2
for(int i=0; i<matrix1.length; i++)
for(int j=0; j<matrix1[i].length; j++) {
matrix1[i][j] = (int)(Math.random() * 10);
matrix2[i][j] = (int)(Math.random() * 10);
}
// add two matrices and print the result
int[][] resultMatrix = addMatrix(matrix1, matrix2);
System.out.println("The addition of the matrices is
");
printResult(matrix1, matrix2, resultMatrix, '+');

// Multiply two matrices and perint the result


resultMatrix = multiplyMatrix(matrix1, matrix2);
System.out.println("\nThe multiplication of the
matrices is ");
printResult(matrix1, matrix2, resultMatrix, '*');
}
/** The method for adding two matrices */
public static int[][] addMatrix(int[][] m1, int[][]
m2) {
int[][] result = new int[m1.length][m1[0].length];
for(int i=0; i<result.length; i++)
for(int j=0; j<result[0].length; j++)
result[i][j] = m1[i][j] + m2[i][j];
return result;
}
/** The method for multiplying two matrices */
public static int[][] multiplyMatrix(int[][] m1,
int[][] m2) {
int[][] result = new int[m1.length][m2[0].length];
for(int i=0; i<m1.length; i++)
for(int j=0; j<result.length; j++)
for(int k=0; k<result[0].length; k++)
result[i][j] += m1[i][k] * m2[k][j];
return result;
}
/** print result */
public static void printResult(
int[][] m1, int[][] m2, int[][] m3, char op) {
for (int i=0; i<m1.length; i++) {
for(int j=0; j<m1[0].length; j++)
System.out.print(" " + m1[i][j]);
if(i==m1.length / 2)
System.out.print(" " + op + "");
else
System.out.print( " " );
for(int j=0; j<m2[0].length; j++)
System.out.print(" " + m2[i][j]);
if(i==m1.length / 2)
System.out.print(" =");
else
System.out.print( " " );
for(int j=0; j<m3[0].length; j++)
System.out.print(" " + m3[i][j]);
System.out.println();
}
}
}

5.10 GUI: Drawing Ovals


Depending on whether you wish to draw an oval in outline or filled solid, you can
use either the drawOval or the fillOval method. Since an oval in Java is drawn
based on its bounding rectangle , give the parameters as if you were drawing a
rectangle.
Here is the method for drawing oval:
drawOval(int x, int y, int w, int h);
To draw a filled oval, use the following method:
fillOval(int x, int y, int w, int h);

(x, y)

The drawOval method draws an oval based on its bounding rectangle


Example: The following program is an example of how to draw ovals
The program:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;

public class DrawOvals extends JFrame {


public DrawOvals() {
setTitle("DrawOvals");
getContentPane().add(new OvalsPanel());
}
/** Main method */
Public static void main(String[] args) {
DrawOvals frame = new DrawOvals();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
frame.setVisible(true);
}
}

// The class for drawing the ovals on a panel


class OvalsPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0,0,10,10);
g.drawRect(0,0,20,50);

g.drawOval(5, 5, getWidth() / 2 - 10, getHeight()


/ 2 - 10);
g.setColor(Color.red);
g.drawOval(getWidth() / 2 + 5, 5, getWidth() / 2 -
10,
getHeight() / 2 - 10);
g.setColor(Color.yellow);
g.fillOval(5, getHeight() / 2 + 5, getWidth() / 2
- 10,
getHeight() / 2 - 10);
g.setColor(Color.orange);
g.fillOval(getWidth() / 2 + 5, getHeight() / 2 +
5,
getWidth() / 2 - 10, getHeight() / 2 - 10);
}
}
The output:
g.drawOvel(40,40,120,120);
g.drawOvel(50,50,100,100);
Drawing Arcs
Like an oval, an arc is drawn based on its bounding rectangle. An arc is conceived
as part of an oval. The methods to draw or fill an arc as follows:
drawArc(int x, int y, int w, int h, int angle1, int
angle2);
fillArc(int x, int y, int w, int h, int angle1, int
angle2);
Parameters x, y, w, and h are the same as in the drawOval method; parameter
angle1 is the starting angle; angle2 is the spanning angle (i.e. the angle covered
by the arc). angles are measured in degrees and follow the usual mathematical
conventions

The drawArc method draws an arc based on an oval with specified angles.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
publicclass DrawArcs extends JFrame {
public DrawArcs() {
setTitle("DrawArcs");
getContentPane().add(new ArcsPanel());
}
/** Main method */
publicstaticvoid main(String[] args) {
DrawArcs frame = new DrawArcs();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 300);
frame.setVisible(true);
}
}
// The class for drawing arcs on a panel
class ArcsPanel extends JPanel {
// Draw four blazes of a fan
protectedvoid paintComponent(Graphics g) {
super.paintComponent(g);

int xCenter = getWidth() / 2;


int yCenter = getHeight() / 2;
int radius =
(int)(Math.min(getWidth(), getHeight()) * 0.4);

int x = xCenter - radius;


int y = yCenter - radius;

g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);


g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
}}
Drawing Polygons and Polylines
Java enables you to draw a polygon and polyline by using the direct method or
by using the Polygon object. The direct method draws a polygon by specifying all
the points, using the following methods:
drawPolygon(x, y, n);
drawPolyline(x, y, n);
fillPolygon(x, y, n);
Parameters x and y are arrays representing x-coordinates and y-coordinates, and
n indicates the number of points. For example:
int[] x = {40, 70, 60, 45, 20};
int[] y = {20, 40, 80, 45, 60};
g.drawPolygon(x, y, x.length);

(x[0], y[0])
(x[1], y[1])
(x[3], y[3])

(x[4], y[4])
(x[2], y[2])

g.drawPolyline(x, y, x.length);
(x[0], y[0])
(x[1], y[1])
(x[3], y[3])

(x[4], y[4])
(x[2], y[2])

Sheet 5

1) How do you declare and create an array?


2) Identify and fix the errors in the following code:
public class Test {
public static void main(String[] args) {
double[] r;
for (int i=0; i < r.length(); i++);
r(i) = Math.random * 100;
}
}
5) What is the output of the following code?
int[][] array = new int[5][6];
int[] x = {1, 2};
array[0] = x;
System.out.println("array[0][1] is " + array[0][1];

6) Write a program that will read ten integers and display them in reverse order.
7) Write a method that sums all the integers in the major diagonal in a matrix of
integers. Use {{1,2,4,5}, {6,7,8,9}, {10,11,12,13}, {14,15,16,17}} to test the
method.
8) Write a program that reads student scores, gets the best score, and then assigns
grades based on the following scheme: Grade is A if score is best; Grade is
B if score is best ; Grade is C if score is best ; Grade is D if score is best ;
Grade is F otherwise. The program prompts the user to enter the total number
of students, then prompts the user to enter all of the scores, and concludes by
displaying the grades. Here is a sample run:
9) Write two overloaded methods that return the average of an array with the
following headers:
public static intaverage(int[] array)
public static doubleaverage(double[] array)
Write a test program that prompts the user to enter ten double values, invokes this
method, and displays the average value.
10) Write a method that returns the index of the smallest element in an array of
integers. If the number of such elements is greater than 1, return the smallest
index.
11) Write a method that returns the sum of all the elements in a specified column
in a matrix using the following header: public static
doublesumColumn(double[][] m, intcolumnIndex) Write a test program that
reads a 3-by-4 matrix and displays the sum of each column.
12)creating jframe to draw rainbow.

You might also like