Download int list[]

Document related concepts
no text concepts found
Transcript
First Data Structure Definition
A data structure is a data type whose
components are smaller data structures
and/or simple data types.
Data Structure Starting Point
Any data type that can store more than
one value is a data structure.
First Array Definition
An array is a data structure with one, or
more, elements of the same type.
A one-dimensional
array is frequently
also called a vector.
A two-dimensional
array is frequently
also called a matrix.
First Record Definition
A record is a data structure with one,
or more, elements, called fields, of the
same or different data types.
File Definition
A file is an internal data structure - with an
unspecified number of elements of the same
type - assigned to an external file name.
The file data structure
allows transfer of data
between internal and
external storage.
Stack Definition
A stack is a data structure
with elements of the same
type.
Data elements of the stack
data structure can only be
accessed (stored or
retrieved) at one end of the
stack in a LIFO (Last In,
First Out) manner.
Improved Data Structure Definition
A data structure is a data type whose
components are smaller data structures
and/or simple data types.
The storing and retrieval of the data elements
is performed by accessing methods that
characterize the data structure.
Improved Array Definition
An array is a data structure with a fixed
number of elements of the same type.
Every element of the array can be
accessed directly.
Array Example
[16]
Ingrid
[17]
Darlene
[18]
Gene
[19]
Sean
[20]
Stephanie
[11]
Holly
[12]
Blake
[13]
Michelle
[14]
Remy
[15]
Haley
[06]
Diana
[07]
Jessica
[08]
David
[09]
Anthony
[10]
Alec
[01]
Isolde
[02]
John
[03]
Greg
[04]
Maria
[05]
Heidi
Defining Static Arrays
int list[ ];
list = new int[10];
// declares the array list identifier
// allocates memory for 10 integers
char names[ ];
names = new char[25];
// declares the names array identifier
// allocates memory for 25 characters
double grades[ ];
// declares the grades array identifier
grades = new double[50]; // allocates memory for 50 doubles
Defining Static Arrays
Preferred Method
int list[ ] = new int[10];
char names[ ] = new char[25];
double grades[ ] = new double[50];
// Java1201.java
// This program demonstrates how to declare an array of integers.
// Note how each element of the array defaults to zero.
// Java allows the display of uninitialized objects because object
// elements get assigned values from the default constructor.
public class Java1201
{
public static void main(String args[])
{
int list[];
// declares the array object identifier
list = new int[10]; // allocates memory for 10 array elements
for (int k = 0; k < 10; k++)
System.out.println("list[" + k + "] = " + list[k]);
System.out.println();
0
1
2
3
4
5
6
7
8
9
}
0 0 0 0 0 0 0 0 0 0
}
Array Index Note
Java arrays indicate individual elements with
an index inside two brackets, following the
array identifier, like list[k]
The array index is always an integer and
starts at 0.
In an array of N elements, the largest index is
N-1.
// Java1202.java
// This program is almost identical to Java1201. The difference
// is that the array declaration and array definition to allocate
// memory is done in one program statement.
public class Java1202
{
public static void main(String args[])
{
int list[] = new int[10];
// combined array declaration and definition
for (int k = 0; k < 10; k++)
System.out.println("list[" + k + "] = " + list[k]);
System.out.println();
}
}
0
1
2
3
4
5
6
7
8
9
0
0
0
0
0
0
0
0
0
0
// Java1203.java
// This program demonstrates how to initialize array elements.
// The <new> operator is not necessary in this case.
public class Java1203
{
public static void main(String args[])
{
int list[] = {11,22,33,44,55,66,77,88,99};
for (int k = 0; k < 9; k++)
System.out.println("list[" + k + "] = " + list[k]);
System.out.println();
}
}
0
1
2
3
4
5
6
7
8
11 22 33 44 55 66 77 88 99
// Java1204.java
// This program demonstrates how to declare an array of characters.
// Are the array elements initialized to any kind of value?
public class Java1204
{
public static void main(String args[])
{
int k;
char list1[] = new char[5];
for (k = 0; k < 5; k++)
System.out.println("list1[" + k + "] = " + list1[k]);
System.out.println();
char list2[] = {'c','h','a','r'};
for (k = 0; k < 4; k++)
System.out.println("list2[" + k + "] = " + list2[k]);
System.out.println();
0 1 2 3 4
0 1 2 3
list1
list2
}
? ? ? ? ?
c h a r
}
// Java1205.java
// The purpose of this program is to investigate the type of character
// that is used to initialize a character array.
// Is it no-character-at-all or a blank space?
public class Java1205
{
public static void main(String args[])
{
char List1[] = new char[10];
System.out.print("Start");
for (int K = 0; K < 10; K++)
System.out.print(List1[K]);
System.out.println("End");
System.out.println();
} 1
0
2
3
4
5
6
7
8
9
}<sp> <sp> <sp> <sp> <sp> <sp> <sp> <sp> <sp> <sp>
// Java1206.java
// This program demonstrates how String objects are initialized,
// both without and with specified array values.
public class Java1206
{
public static void main(String args[])
{
String list1[] = new String[5];
for (int k = 0; k < 5; k++)
System.out.println("list[" + k + "] = " + list1[k]);
System.out.println();
String list2[] = {"AAA","BBB","CCC","DDD","EEE"};
for (int k = 0; k < 5; k++)
System.out.println("list2[" + k + "] = " + list2[k]);
0
1
2
3
4
0 System.out.println();
1
2
3
4
list1
} null null null null null list2 AAA BBB CCC DDD EEE
}
// Java1207.java
// This program fills an integer array with a random set of numbers.
import java.util.Random;
public class Java1207
{
public static void main(String args[])
{
int list[] = new int[20];
Random random = new Random(12345);
for (int k = 0; k < 20; k++)
list[k] = random.nextInt(900) + 100;
for (int k = 0; k < 20; k++)
System.out.println("list[" + k + "] = " + list[k]);
System.out.println();
0
1}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
} 680 241 928 455 284 575 802 701 889 717 142 890 206 312 584 687 803
851
18
19
432 775
// Java1208.java
// This program introduces the length field to determine the
// number of elements in the array. Remove the comments from line
// 16 to observe what happens when the length field is altered.
public class Java1208
{
public static void main(String args[])
{
String names[] = {"Joe","Tom","Sue","Meg"};
int n = names.length;
// data field access; not a method call
System.out.println("There are " + n + " array elements.");
for(int k = 0; k < n; k++)
System.out.println("names[" + k + "] = " + names[k]);
// names.length = 10; // Line 16
System.out.println();
}
}
0
1
2
3
Joe
Tom
Sue
Meg
// Java1209.java
// This program demonstrates how to create an array of random strings.
import java.util.Random;
public class Java1209
{
public static void main(String args[])
{
Random random = new Random(12345);
int rndInt;
String names[] = {"AA","BB","CC","DD","EE","FF","GG","HH","II","JJ"};
for(int k = 1; k < 15; k++)
{
rndInt = random.nextInt(names.length);
System.out.println("names[" + rndInt + "] = " + names[rndInt]);
}
System.out.println();
0
}AA
}
1
2
3
4
5
6
7
8
9
BB
CC
DD
EE
FF
GG
HH
II
JJ
// Java1210.java
// This program is the first stage in the List class. At this stage the
// List class only initializes an array and displays its default values.
public class Java1210
{
public static void main(String args[])
{
List1 listA = new List1(10);
listA.display();
List1 listB = new List1(15);
listB.display();
}
}
class List1
{
private int intArray[]; // stores array elements
private int size;
// number of elements in the array
public List1(int s)
{
size = s;
intArray = new int[size];
}
public void display()
{
for (int k = 0; k < size; k++)
System.out.print(intArray[k] + " ");
System.out.println();
}
}
// Java1211.java
// This is the second stage of the List class.
// A method for assigning random integers has been added.
import java.util.Random;
public class Java1211
{
public static void main(String args[])
{
List2 listA = new List2(10);
listA.Display();
listA.Assign();
listA.Display();
System.out.println();
}
}
class List2
// shown on next slide
class List2
{
private int intArray[]; // stores array elements
private int size;
// number of elements in the array
public List2(int s)
{
System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES");
size = s;
intArray = new int[size];
}
public void Assign()
{
System.out.println("\nASSIGNING RANDOM VALUES TO LIST OBJECT");
Random random = new Random(12345);
for (int k = 0; k < size; k++)
intArray[k] = random.nextInt(9000) + 1000;
}
public void Display()
{
System.out.println("\nDISPLAYING ARRAY ELEMENTS");
for (int k = 0; k < size; k++)
System.out.print(intArray[k] + " ");
System.out.println();
}
}
// Java1212.java
// A second "overloaded" constructor has been added to the third stage of the
// List class. The second constructor specifies the initial array values.
import java.util.Random;
public class Java1212
{
public static void main(String args[])
{
List3 listA = new List3(10);
listA.Display();
List3 listB = new List3(10,999);
listB.Display();
listB.Assign();
listB.Display();
System.out.println();
}
}
class List3
// continued on next slide
class List3
{
private int intArray[];
private int size;
public List3(int s)
{
// stores array elements
// number of elements in the array
System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES");
size = s;
intArray = new int[size];
}
public List3(int s, int n)
{
System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH SPECIFIED VALUES");
size = s;
intArray = new int[size];
for (int k = 0; k < size; k++)
intArray[k] = n;
}
public void Assign()
{
System.out.println("\nASSIGNING RANDOM VALUES TO LIST OBJECT");
Random random = new Random(12345);
for (int k = 0; k < size; k++)
intArray[k] = random.nextInt(9000) + 1000;
}
public void Display()
{
System.out.println("\nDISPLAYING ARRAY ELEMENTS");
for (int k = 0; k < size; k++)
System.out.print(intArray[k] + " ");
System.out.println();
}
}
AP Exam Alert
One-dimensional arrays will be tested
for the "A-level" and "AB-level" APCS
examination.
Two-dimensional
arrays will only be
tested for the "AB-level"
APCS examination.
// Java1213.java
// This program introduces the Java5.0 enhanced <for> loop
// with an <int> array.
public class Java1213
{
public static void main(String args[])
{
System.out.println("Java1213\n");
int list[] = {11,22,33,44,55,66,77,88,99};
for (int k = 0; k < 9; k++)
// Old <for> loop syntax
System.out.print(list[k] + " ");
System.out.println("\n\n");
for (int item: list)
// New <for> loop syntax
System.out.print(item + " ");
System.out.println("\n\n");
}
}
// Java1214.java
// This program uses the Java 5.0 <for> loop with a <String> array.
public class Java1214
{
public static void main(String args[])
{
System.out.println("Java1214\n");
String names[] = {"Tom","Sue","Joe","Jan","Bob","Lee","Ann","Meg"};
for (int k = 0; k < 8; k++)
System.out.print(names[k] + " ");
System.out.println("\n\n");
// Old <for> loop syntax
for (String name: names)
// New <for> loop syntax
System.out.print(name + " ");
System.out.println("\n\n");
}
}
// Java1215.java
// This program demonstrates a very generalized <for..each> loop usage
// with the <Object> class.
public class Java1215
{
public static void main(String args[])
{
System.out.println("Java1215\n");
String names[] = {"Tom","Sue","Joe","Jan","Bob","Lee","Ann","Meg"};
for (int k = 0; k < 8; k++)
System.out.print(names[k] + " ");
System.out.println("\n\n");
for (Object obj: names)
System.out.print(obj + " ");
System.out.println("\n\n");
}
}
Enhancing the for Loop
The enhanced for loop is called the for .. each loop.
This loop structure is available in Java 5.0
The new loop structure does not replace the older for
loop, because it is not possible to access specific array
elements.
int numbers[ ] = {1,2,3,4,5,6,7,8,9};
for (int number: numbers)
System.out.print(number + "
");
AP Exam Alert
The Arrays class is not part of the AP Java Subset
and will not be tested.
Students are expected to know how to use and
implement array algorithms, such as traversing,
element access, sorting and searching.
In this chapter these array algorithms are used with
the provided Arrays class methods.
In a future Algorithm chapter you will learn how to
implement these methods yourself.
// Java1216.java
// This program introduces the static <Arrays> class.
// In this program the <toString> method is used to display the array elements.
import java.util.Arrays;
// necessary to use the <Arrays> class
public class Java1216
{
public static void main (String args[])
{
System.out.println("Java1216\n");
int list1[] = {11,22,33,44,55,66,77,88,99};
double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9};
char list3[] = {'A','B','C','D','E','F','G','H','I'};
String list4[] = {"AA","BB","CC","DD","EE","FF","GG","HH","II"};
System.out.println(Arrays.toString(list1));
System.out.println(Arrays.toString(list2));
System.out.println(Arrays.toString(list3));
System.out.println(Arrays.toString(list4));
System.out.println("\n\n");
}
}
Class Arrays
Method toString
Method toString displays the elements of
an array object separated by commas and
bounded by square brackets. [ ]
int list[] = {11,22,33,44,55,66,77,88,99};
System.out.println(Arrays.toString(list));
// Java1217.java
// This program demonstrates the <fill> method of the <Arrays> class.
// The <fill> method assigns the same value to every array element.
import java.util.Arrays;
// necessary to use the <Arrays> class
public class Java1217
{
public static void main (String args[])
{
System.out.println("Java1217\n");
int list1[] = new int[10];
double list2[] = new double[10];
char list3[] = new char[10];
String list4[] = new String[10];
Arrays.fill(list1,123);
Arrays.fill(list2,1.23);
Arrays.fill(list3,'Q');
Arrays.fill(list4,"USA");
System.out.println(Arrays.toString(list1));
System.out.println(Arrays.toString(list2));
System.out.println(Arrays.toString(list3));
System.out.println(Arrays.toString(list4));
System.out.println("\n\n");
}
}
Class Arrays
Method fill
Method fill assigns the same
value to every array element.
int list1[] = new int[10];
double list2[] = new double[10];
char list3[] = new char[10];
String list4[] = new String[10];
Arrays.fill(list1,123);
Arrays.fill(list2,1.23);
Arrays.fill(list3,'Q');
Arrays.fill(list4,"USA");
// Java1218.java
// This program demonstrates the <sort> method of the <Arrays> class.
// Method <sort> arranges array elements in ascending order.
import java.util.Arrays;
// necessary to use the <Arrays> class
public class Java1218
{
public static void main (String args[])
{
System.out.println("Java1218\n");
int list1[] = {11,99,22,88,33,77,44,66,55};
double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9};
char list3[] = {'A','I','B','H','C','G','D','F','E'};
String list4[] = {"AA","II","BB","HH","CC","GG","DD","FF","EE"};
String list5[] =
{"aardvark","bobcat","cougar","dog","ELEFANT","FOX","GORILLA","HARE"};
Arrays.sort(list1);
Capital Letters have numeric
Arrays.sort(list2);
Arrays.sort(list3);
code values from 65-90.
Arrays.sort(list4);
Arrays.sort(list5);
System.out.println(Arrays.toString(list1));
System.out.println(Arrays.toString(list2));
System.out.println(Arrays.toString(list3));
System.out.println(Arrays.toString(list4));
System.out.println(Arrays.toString(list5));
System.out.println("\n\n");
}
}
Lowercase letters have numeric
code values from 97-112.
If lowercase letters are sorted
together with capital letters, the
capitals will come first because
of the smaller code values.
Class Arrays
Method sort
Method sort arranges the array elements in ascending
order. String and character array elements are sorted
in ascending order of the numerical code values.
Incorrect processing may occur if string values are
mixed upper-case and lower-case.
int list1[] = {11,99,22,88,33,77,44,66,55};
double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9};
char list3[] = {'A','I','B','H','C','G','D','F','E'};
Arrays.sort(list1);
Arrays.sort(list2);
Arrays.sort(list3);
// Java1219.java
// This program demonstrates the <binarySearch> method of the <Arrays> class.
// Method <binarySearch> returns the index of a search element if it exists,
// and returns a negative index value otherwise.
import java.util.Arrays;
// necessary to use the <Arrays> class
public class Java1219
{
public static void main (String args[])
{
System.out.println("Java1219\n");
int list[] = {11,99,22,88,33,77,44,66,55};
System.out.println(Arrays.toString(list));
Arrays.sort(list);
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Index of 33 is " + Arrays.binarySearch(list,33));
System.out.println("Index of 11 is " + Arrays.binarySearch(list,11));
System.out.println("Index of 99 is " + Arrays.binarySearch(list,99));
System.out.println("Index of 10 is " + Arrays.binarySearch(list,10));
System.out.println("\n\n");
}
}
// Java1220.java
// This program demonstrates that an array must be sorted before
// the <binarySearch> method is called.
// Erroneous indexes are returned if the list is
import java.util.Arrays;
not sorted!!!
// necessary to use the <Arrays> class
public class Java1220
{
public static void main (String args[])
{
System.out.println("Java1220\n");
int list[] = {11,99,22,88,33,77,44,66,55};
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Index of 33 is " + Arrays.binarySearch(list,33));
System.out.println("Index of 11 is " + Arrays.binarySearch(list,11));
System.out.println("Index of 99 is " + Arrays.binarySearch(list,99));
System.out.println("Index of 10 is " + Arrays.binarySearch(list,10));
System.out.println("\n\n");
}
}
Class Arrays
Method binarySearch
Method binarySearch searches the elements of an array
object for a specified value.
The index of the array element is returned, if the element is
found and a negative index is returned otherwise.
Array elements must be sorted, otherwise the
binarySearch method returns incorrect information.
int list[] = {11,99,22,88,33,77,44,66,55};
System.out.println("Index of 33 is " + Arrays.binarySearch(list,33));
// Java1221.java
// This program demonstrates how an argument can be entered
// from the command line using the args[] array.
// This program expects a single argument.
public class Java1221
{
public static void main(String args[])
{
System.out.println("Java1221\n");
System.out.print("Entered at command line: ");
System.out.println(args[0]);
}
}
// Java1222.java
// This program demonstrates how multiple arguments can be
// entered from the command line using the args[] array.
// This program expects three separate single arguments.
public class Java1222
{
public static void main(String args[])
{
System.out.println("Java1222\n");
System.out.println("Entered at command line:\n");
System.out.println("args[0]: " + args[0]);
System.out.println("args[1]: " + args[1]);
System.out.println("args[2]: " + args[2]);
}
}
Working with args
The Java main method always includes (String args[ ])
The args array stores String values entered at the prompt.
There are many, many ways to do interactive input in Java.
While the Scanner class will let you enter int and double
values, the vast majority of Java input methods will only let
you enter String values.
It is possible to convert entered string values to numerical
values by using Integer.parseInt & Double.parseDouble
// Java1223.java
// This program reviews the use of the <Integer> class with the
// <parseInt> method to convert strings entered at the command line
// prompt to integers.
public class Java1223
{
public static void main(String args[])
{
System.out.println("Java1223\n");
int nr1 = Integer.parseInt(args[0]);
int nr2 = Integer.parseInt(args[1]);
int sum = nr1 + nr2;
System.out.println(nr1 + " + " + nr2 + " = " + sum);
}
}
main Method Arguments
The next program uses main method arguments.
You will need to turn on this feature in JCreator.
main Method Arguments
Step 2
main Method Arguments
Step 3
main Method Arguments
Step 4
main Method Arguments
Step 5
main Method Arguments
Step 6
// Java1224.java
// This program reviews the use of the <Double> class with the
// <parseDouble> method to convert strings entered at the command
// line prompt to real numbers.
public class Java1224
{
public static void main(String args[])
{
System.out.println("Java1224\n");
double nr1 = Double.parseDouble(args[0]);
double nr2 = Double.parseDouble(args[1]);
double sum = nr1 + nr2;
System.out.println(nr1 + " + " + nr2 + " = " + sum);
}
}
Important Note
args was shown because it is an example of an array.
However, we will continue to use the Scanner class because
it is easier to work with.
Please go back to
• Configure
• Options
• JDK Tools
• Default
• Edit
• Parameters
and remove the check for
Prompt for main
method arguments
// Java1225.java
// STATIC IMPORTS #1
// This program introduces static imports.
// With Java 5.0 it is now possible to use class methods without the class identifier.
// In this example the <System> class name is not necessary.
import static java.lang.System.*; // necessary to eliminate the <System> identifier
public class Java1225
{
public static void main (String args[])
{
System.out.println("Java1225\n");
///// JAVA 1.4 /////
System.out.println("This demonstrates Java 1.4");
System.out.println();
System.out.println("The static class identifier <System> must be used.\n\n");
///// JAVA 5.0 /////
out.println("This demonstrates Java 5.0");
out.println();
out.println("It is not necessary to use the <System> class identifier.\n\n");
}
}
// Java1226.java
// STATIC IMPORTS #2
// This program introduces more static imports.
// In this example the <Math> and <System class names are not necessary.
import static java.lang.System.*;
// necessary to eliminate the <System> identifier
import static java.lang.Math.*; // necessary to eliminate the <Math> identifier
public class Java1226
{
public static void main (String args[])
{
System.out.println("Java1226\n");
///// JAVA 1.4 /////
System.out.println("Math class methods are a good example of working with static imports.");
System.out.println();
System.out.println("The square root of 100 is " + Math.sqrt(100));
System.out.println("13 to the 4th power is
" + Math.pow(13,4));
System.out.println("\n\n");
///// JAVA 5.0 /////
out.println("Math class methods are a good example of working with static imports.");
out.println();
out.println("The square root of 100 is " + sqrt(100));
out.println("13 to the 4th power is
" + pow(13,4));
out.println("\n\n");
}
}
// Java1227.java
// STATIC IMPORTS #3
// This program introduces more static imports.
// In this example the <Arrays> and <System> class names are "sometimes" not necessary.
import java.util.Arrays;
// necessary to use the <Arrays> class
import static java.lang.System.*;
// necessary to eliminate the <System> identifier
import static java.util.Arrays.*; // necessary to eliminate the <Arrays> identifier
public class Java1227
{
public static void main (String args[])
{
System.out.println("Java1227\n");
int list[] = {12,56,34,91,65,27,45,70,85};
///// JAVA 1.4 /////
System.out.println(Arrays.toString(list));
Arrays.sort(list);
System.out.println(Arrays.toString(list));
System.out.println("\n\n");
///// JAVA 5.0 /////
out.println(Arrays.toString(list));
sort(list);
out.println(Arrays.toString(list));
out.println("\n\n");
}
}
// this is intentional; check next program
// this is intentional; check next program
// Java1228.java
STATIC IMPORTS #4
// This program demonstrates a potential problem with static imports.
// The <toString> method without the <Arrays> identifier confuses the Java compiler.
// The <Object> class has a <toString> method, as do many other classes.
// This program will not compile.
import java.util.Arrays;
// necessary to use the <Arrays> class
import static java.lang.System.*;
// necessary to eliminate the <System> identifier
import static java.util.Arrays.*;
// necessary to eliminate the <Arrays> identifier
public class Java1228
{
public static void main (String args[])
{
System.out.println("Java1228\n");
int list[] = {12,56,34,91,65,27,45,70,85};
///// JAVA 1.4 /////
System.out.println(Arrays.toString(list));
Arrays.sort(list);
System.out.println(Arrays.toString(list));
System.out.println("\n\n");
///// JAVA 5.0 /////
out.println(toString(list));
sort(list);
out.println(toString(list));
out.println("\n\n");
}
}