Download presentation
Presentation is loading. Please wait.
Published byCleopatra Nash Modified over 8 years ago
1
Copyright 2008 by Pearson Education Java Programing Array
2
Arrays array: object that stores many values of the same type. element: One value in an array. index: A 0-based integer to access an element from an array. index0123456789 value1249-226517-684723 element 0element 4element 9
3
Array declaration type [] name = new type [ length ]; Example: int[] numbers = new int[10]; index0123456789 value0000000000
4
Array declaration, cont. The length can be any integer expression. int x = 2 * 3 + 1; int[] data = new int[x % 5 + 2]; Each element initially gets a "zero-equivalent" value. TypeDefault value int0 double0.0 booleanfalse String or other object null (means, "no object")
5
What happens if … Valid code: int k=7; long[] primes = new long[k]; Invalid Code: int k; long[] primes =new long[k]; Compilation Output: MorePrimes.java:6: variable k might not have been initialized long[] primes = new long[k]; ^
6
Accessing elements name [ index ]// access name [ index ] = value ;// modify Example: numbers[0] = 27; numbers[3] = -6; System.out.println(numbers[0]); if (numbers[3] < 0) { System.out.println("Element 3 is negative."); } index0123456789 value0000000000 index0123456789 value2700-6000000
7
Arrays of other types double[] results = new double[5]; results[2] = 3.4; results[4] = -0.5; boolean[] tests = new boolean[6]; tests[3] = true; index01234 value0.0 3.40.0-0.5 index012345 valuefalse truefalse
8
Out-of-bounds Legal indexes: between 0 and the array's length - 1. Reading or writing any index outside this range will throw an ArrayIndexOutOfBoundsException. Example: int[] data = new int[10]; System.out.println(data[0]); // okay System.out.println(data[9]); // okay System.out.println(data[-1]); // exception System.out.println(data[10]); // exception index0123456789 value0000000000
9
Accessing array elements int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; int x = numbers[1]; numbers[x] = 42; numbers[numbers[6]] = 11; // use numbers[6] as index x numbers x3 index0123456789 value index0123456789 value0411429902000
10
Arrays and for loops It is common to use for loops to access array elements. for (int i = 0; i < 8; i++) { System.out.print(numbers[i] + " "); } System.out.println(); // output: 0 4 11 0 44 0 0 2 Sometimes we assign each element a value in a loop. for (int i = 0; i < 8; i++) { numbers[i] = 2 * i; } index01234567 value02468101214
11
The length field An array's length field stores its number of elements. name.length for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } // output: 0 2 4 6 8 10 12 14 It does not use parentheses like a String's.length(). What expressions refer to: The last element of any array? The middle element?
12
Weather question Use an array to solve the weather problem: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.6 4 days were above average.
13
Weather answer // Reads temperatures from the user, computes average and # days above average. import java.util.*; public class Weather { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How many days' temperatures? "); int days = console.nextInt(); int[] temperatures = new int[days]; // array to store days' temperatures int sum = 0; for (int i = 0; i < days; i++) { // read/store each day's temperature System.out.print("Day " + (i + 1) + "'s high temp: "); temperatures[i] = console.nextInt(); sum += temperatures[i]; } double average = (double) sum / days; int count = 0; // see if each day is above average for (int i = 0; i < days; i++) { if (temperatures[i] > average) { count++; } // report results System.out.printf("Average temp = %.1f\n", average); System.out.println(count + " days above average"); }
14
A multi-counter problem Problem: Examine a large integer and count the number of occurrences of every digit from 0 through 9. Example: The number 229231007 contains: two 0s, one 1, three 2s, one 7, and one 9. We could declare 10 counter variables for this... int counter0, counter1, counter2, counter3, counter4, counter5, counter6, counter7, counter8, counter9; Yuck!
15
A multi-counter problem A better solution is to use an array of size 10. The element at index i will store the counter for digit value i. for integer value 229231007, our array should store: The index at which a value is stored has meaning. Sometimes it doesn't matter. What about the weather case? index0123456789 value2130000101
16
Creating an array of tallies int num = 229231007; int[] counts = new int[10]; while (num > 0) { // pluck off a digit and add to proper counter int digit = num % 10; counts[digit]++; num = num / 10; } index0123456789 value2130000101
17
Array histogram question Given a file of integer exam scores, such as: 82 66 79 63 83 Write a program that will print a histogram of stars indicating the number of students who earned each unique exam score. 85: ***** 86: ************ 87: *** 88: * 91: ****
18
Histogram variations Curve the scores; add a fixed number to each score. (But don't allow a curved score to exceed the max of 101.) Chart the data with a DrawingPanel. window is 100px tall 2px between each bar 10px tall bar for each student who earned that score
19
Array histogram answer // Reads an input file of test scores (integers) and displays a // graphical histogram of the score distribution. import java.awt.*; import java.io.*; import java.util.*; public class Histogram { public static final int CURVE = 5; // adjustment to each exam score public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("midterm.txt")); int[] counts = new int[101]; // counters of test scores 0 - 100 while (input.hasNextInt()) { // read file into counts array int score = input.nextInt(); score = Math.min(score + CURVE, 100); // curve the exam score counts[score]++; // if score is 87, then counts[87]++ } for (int i = 0; i < counts.length; i++) { // print star histogram if (counts[i] > 0) { System.out.print(i + ": "); for (int j = 0; j < counts[i]; j++) { System.out.print("*"); } System.out.println(); }...
20
Array histogram solution 2... // use a DrawingPanel to draw the histogram DrawingPanel p = new DrawingPanel(counts.length * 3 + 6, 200); Graphics g = p.getGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < counts.length; i++) { g.drawLine(i * 3 + 3, 175, i * 3 + 3, 175 - 5 * counts[i]); }
21
Arrays of Arrays Two-Dimensional arrays float[][] temperature=new float[10][365]; 10 arrays each having 365 elements First index: specifies array (row) Second Index: specifies element in that array (column) In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
22
Initializing Array of Arrays int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} }; //5 arrays with 5 elements each
23
Arrays of Arrays of Varying Length All arrays do not have to be of the same length float[][] samples; samples=new float[6][];//defines # of arrays samples[2]=new float[6]; samples[5]=new float[101]; Not required to define all arrays
24
Initializing Varying Size Arrays int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; //Three arrays //First array has 3 elements //Second array has 2 elements //Third array has 5 elements
25
25 SOME USEFUL ARRAY OPERATIONS Finding the Average of the Values in a Numeric Array To find the average of the values in a numeric array, first find the sum of the values in the array. Then divide this sum by the number of elements in the array.
26
Examples Using Arrays Using arrays to analyze survey results 40 students rate the quality of food 1-10 Rating scale: 1 mean awful, 10 means excellent Place 40 responses in array of integers Summarize results
27
Sorting Arrays Sorting data Attracted intense research in computer-science field Bubble sort Smaller values “bubble” their way to top of array Larger values “sink” to bottom of array Use nested loops to make several passes through array Each pass compares successive pairs of elements Pairs are left along if increasing order (or equal) Pairs are swapped if decreasing order
28
Searching Arrays: Linear Search and Binary Search Searching Finding elements in large amounts of data Determine whether array contains value matching key value Linear searching Binary searching
29
Searching Arrays: Linear Search and Binary Search Linear search Compare each array element with search key If search key found, return element index If search key not found, return –1 (invalid index) Works best for small or unsorted arrays Inefficient for larger arrays
30
Searching Arrays: Linear Search and Binary Search Binary search Efficient for large, sorted arrays Eliminates half of the elements in search through each pass Compare middle array element to search key If element equals key Return array index If element is less than key Repeat search on first half of array If element is greater then key Repeat search on second half of array Continue search until element equals search key (success) Search contains one element not equal to key (failure)
31
Multidimensional Arrays A farmer has 10 farms of beans each in 5 countries, and each farm has 30 fields! Three-dimensional array long[][][] beans=new long[5][10][30]; //beans[country][farm][fields]
32
Input/output (I/O) import java.io.*; Create a File object to get info about a file on disk. (This doesn't actually create a new file on the hard disk.) File f = new File("example.txt"); if (f.exists() && f.length() > 1000) { f.delete(); } Method nameDescription canRead() returns whether file is able to be read delete() removes file from disk exists() whether this file exists on disk getName() returns file's name length() returns number of bytes in file renameTo( file ) changes name of file
33
Output to files PrintStream : An object in the java.io package that lets you print output to a destination such as a file. Any methods you have used on System.out (such as print, println ) will work on a PrintStream. Syntax: PrintStream name = new PrintStream(new File(" file name ")); Example: PrintStream output = new PrintStream(new File("out.txt")); output.println("Hello, file!"); output.println("This is a second line of output.");
34
Details about PrintStream PrintStream name = new PrintStream(new File(" file name ")); If the given file does not exist, it is created. If the given file already exists, it is overwritten. The output you print appears in a file, not on the console. You will have to open the file with an editor to see it. Do not open the same file for both reading ( Scanner ) and writing ( PrintStream ) at the same time. You will overwrite your input file with an empty file (0 bytes).
35
System.out and PrintStream The console output object, System.out, is a PrintStream. PrintStream out1 = System.out; PrintStream out2 = new PrintStream(new File("data.txt")); out1.println("Hello, console!"); // goes to console out2.println("Hello, file!"); // goes to file A reference to it can be stored in a PrintStream variable. Printing to that variable causes console output to appear. You can pass System.out as a parameter to a method expecting a PrintStream. Allows methods that can send output to the console or a file.
36
Reading files To read a file, pass a File when constructing a Scanner. Scanner name = new Scanner(new File(" file name ")); Example: File file = new File("mydata.txt"); Scanner input = new Scanner(file); or, better yet: Scanner input = new Scanner(new File("mydata.txt"));
37
Prompting for a file name We can ask the user to tell us the file to read. The file name might have spaces; use nextLine(), not next() // prompt for input file name Scanner console = new Scanner(System.in); System.out.print("Type a file name to use: "); String filename = console.nextLine(); Scanner input = new Scanner(new File(filename)); What if the user types a file name that does not exist?
38
Compiler error w/ files The following program does not compile: import java.io.*; // for File import java.util.*; // for Scanner public class ReadFile { public static void main(String[] args) { Scanner input = new Scanner(new File("data.txt")); String text = input.next(); System.out.println(text); } The following error occurs: ReadFile.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner input = new Scanner(new File("data.txt")); ^
39
Testing for valid input Scanner methods to see what the next token will be: These methods do not consume input; they just give information about the next token. Useful to see what input is coming, and to avoid crashes. MethodDescription hasNext() returns true if there are any more tokens of input to read (always true for console input) hasNextInt() returns true if there is a next token and it can be read as an int hasNextDouble( ) returns true if there is a next token and it can be read as a double
40
Using hasNext methods To avoid exceptions: Scanner console = new Scanner(System.in); System.out.print("How old are you? "); if (console.hasNextInt()) { int age = console.nextInt(); // will not crash! System.out.println("Wow, " + age + " is old!"); } else { System.out.println("You didn't type an integer."); } To detect the end of a file: Scanner input = new Scanner(new File("example.txt")); while (input.hasNext()) { String token = input.next(); // will not crash! System.out.println("token: " + token); }
41
Class Libraries A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment The Java class library is sometimes referred to as the Java API API stands for Application Programming Interface
42
The Java API Get comfortable navigating the online Java API documentation
43
Package A package is a collection of related classes. If the class belongs to a certain package, The file should be in a folder with the same name as package. a class can only be in one package Placing the package declaration at the top of your source file includes these classes in a package with the name that you specify. ex: package graphics; If no package is explicitly declared, Java places your classes into a default package containing all files in the same folder. 43 package racing; class Car { } package racing; class Car { } The Java platform provides an enormous class library,organized as packages. This library is known as the "Application Programming Interface“(API). JAVA API Documentation package graphics; class Button { } package graphics; class Button { }
44
44 Java API packages (a subset). JAVA API Documentation
45
Using classes from Java API 45 Package :java.lang Class Math Package :java.lang Class Integer Package :java.util Class Random Package :javax.swing Class JOptionPane
46
class java.lang.Mathjava.lang.Math class java.lang.Mathjava.lang.Math 46 import java.lang.Math; public class Test { public static void main (String [] arg) { int a=Math.abs(-4); System.out.println("a="+a) ; int b=Math.round(4.6f); int c=Math.max(4,7); double d=Math.random(); } }
47
import javax.swing.JOptionPane; public class Welcome { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Welcome to Java!“); } } 47 Welcome.java
48
import javax.swing.JOptionPane; public class WelcomeInMessageDialogBox { public static void main(String[] args) { String name=JOptionPane.showInputDialog(null, "Plz enter your name “); JOptionPane.showMessageDialog(null, "Welcome "+ name +" to Java!“); } } WelcomeInMessageDialogBox.java 48 Run
49
49 Package :java.lang Class IntegerInteger static int parseInt(String s) Parses the string argument as a signed decimal integer.parseIntString Example 3: Converting Strings to Numbers To convert a string into an int value, use the parseInt method in the Integer class, as follows: int intValue = Integer.parseInt(intString); /////////// String s1=“14”; int i=Integer.parseInt(s1); /////////// String s1=“14”; int i=Integer.parseInt(s1);
50
50 import javax.swing.JOptionPane; public class Adder { public static void main(String[] args) { String num1=JOptionPane.showInputDialog(null, "Please enter first number"); String num2=JOptionPane.showInputDialog(null, "Please enter second number"); int x=Integer.parseInt(num1); int y=Integer.parseInt(num2); int z=x+y; JOptionPane.showMessageDialog(null, "the sum is "+ z); } }
51
51 class java.util.Random RandomRandom( ) Constructor Methods public int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive) import java.util.Random; public class Test { public static void main (String [] arg) { Random rnd=new Random(); int x=0; for(int i=0; i<10;i++) { x=rnd.nextInt(11); System.out.println("x="+ x); } } }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.