1 / 45

Arrays

Arrays. How used???. With loops while… do…while for…. Why used???. To accommodate large volumes of data in memory at once, so that analysis can be performed on them. Declaring an Array. Double[] salesFigure; Long[] idNum; Employee oneWorker;. After you declare an array….

aviv
Download Presentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays

  2. How used??? • With loops • while… • do…while • for…

  3. Why used??? • To accommodate large volumes of data in memory at once, so that analysis can be performed on them

  4. Declaring an Array Double[] salesFigure; Long[] idNum; Employee oneWorker;

  5. After you declare an array… • You still need to set aside memory space oneWorker = new Employee; • The statement above actually creates the oneWorker object and sets aside memory space for it.

  6. We do something similar for arrays double[] salesFigure; • To declare it. Then… salesFigure = new double[20]; • Or, in a single statement… double[] salesFigure = new double[20]; • In the above statement, you are both declaring and creating the array salesFigure[] in which 20 storage locations are set aside for it

  7. Note that this is different from C++ double salesFigure [20]; • Is acceptable in C++, but causes a compiler error in Java

  8. Distinguishing between storage locations • You use a subscript to distinguish between storage locations • A subscript is an integer contained within brackets that indicates one of the arrays’ storage locations • Legal subscripts would be 0 through 19 • Many programming languages begin with 1 as the first subscript—not so, Java salesFigure[0] salesFigure[1] salesFigure[2] salesFigure[3]

  9. Array names.. • Contain references or memory addresses, not the actual contents or value • This is true of all Java objects • This is in contrast to a variable that was a primitive type; such variables actually hold the value

  10. Initializing an Array Int[] someNums = new int[10]; • Here, someNums contains a reference or pointer address to the starting location of the array • The array is initialized to all 0’s because it is a numeric array • Char array elements are initialized to ‘\u0000’ and boolean array elements are initialized to false

  11. Initializations occur at… • Compile time whereas assignments occur at execution time Int[] someNums = new int[10]; • Causes 10 0’s to be placed in the ten storage locations, whereas someNums[0] = 46; • Causes the first such storage location to be assigned the integer value 46 at execution time

  12. Nonzero initializations Int[] tenMult = {10, 20, 30, 40, 50, 60}; • The size of the array is determined by the number of elements you put in the list. This causes the array tenMult[] to be declared and created and initialized • Here you did not need to use the keyword new or the name of the constructor

  13. The power of arrays becomes • Apparent when you use subscripts that are variables rather than subscripts that are constants • Consider tenMult[]

  14. Subscripts starting from 0… • For convenience, you can think of these subscripts as offsets from the starting location of the array. • Int[] tenMult = {10, 20, 30, 40, 50, 60}; tenMult[0] = +=3; tenMult[1] = +=3; tenMult[2] = +=3; tenMult[3] = +=3; tenMult[4] = +=3; What is tenmult[3] now???

  15. The same assignments using for.. for(i=0; i < 5; i++) tenMult[i] += 3; • Does the same thing as the previous five statements • Can also use a symbolic constant as follows: final int FIVE = 5; for(i=0; i < FIVE; i++) tenMult[i] += 3;

  16. The following is also common… for(i=0; i < tenMult.length; i++) tenMult[i] += 3; • Here length is not a method, but a field, an instance variable that is automatically assigned for every array you create for(i=0; i < tenMult.length(); i++) tenMult[i] += 3; • Is Wrong!!!

  17. Enhanced for loop for(int sub = 0; sub < scoreArray.length; ++sub) System.out.println(scoreArray[sub]); For(int val : scoreArray) system.out.println(val); The second statement does the same thing as the first

  18. Using Subscripts with an Array • Is the only way to go for large arrays

  19. Declaring an Array of Objects Instead of … Employee painter, electrician, plumber; Employee bricklayer, roofer, carpetman; Employee[] emp = new employee[6] Here an array named emp holds six employee objects However, these statements do not actually construct those Employee objects

  20. The above assumes… Public class Employee { private int empNum; private double empSal; Employee (int e, double s) { empNum = e; empSal = s; } public int getEmpNum() { return empNum; } public double getSalary() { return empSal; } }

  21. Instead…. You must call the constructor six times final int NUM_EMPLOYEES = 6; final double PAYRATE = 6.35; For(int x = 0; x < NUM_EMPLOYEES; ++x) emp[x] = new Employee(101+x, PAYRATE); For(int x = 0; x < NUM_EMPLOYEES; ++x) system.out.println(emp[x].getEmpNum() + “ “ + emp[x].getSalary());

  22. Searching an Array for an Exact Match

  23. Searching an Array for a Range Match

  24. Passing Arrays to Methods • If you pass an entire array to a method, you are passing by reference, meaning that the starting address of the array is passed to the method and the method can change every element in the array • If you pass a specific element of an array, it is like passing a primitive element and is a pass by value, meaning the actually value is transferred to the method, so the method cannot change the original variable value

  25. Creating Arrays of Strings String [] deptName = {“Accounting”, “Human Resources”, “Sales”}; for(int a=0; a<deptName.length; ++a) System.out.println(deptName[a]);

  26. Sorting Array Elements • The algorithm must do a comparison between the ith element in the list and the i+1st element in the list (adjacent element in the list) • If the pair of elements are not in the correct order, the elements must be swapped: temp = list[i]; List[i] = list[i+1]; List[i+1] = temp;

  27. More sorting • When numbers are sorted from smallest to largest, the order is ascending order • When numbers are sorted from largest to smallest, the order is descending order

  28. Bubble sort int[] someNums = {88, 33, 99, 22, 54}; int b, temp For(b=0; b<someNums.length-1; ++b) if(someNums[b] > someNums[b+1] { temp = someNums[b]; someNums[b] = someNums[b+1]; someNums[b+1] = temp; }

  29. Using Two-Dimensional and Multidimensional Arrays Employee[] someEmps = new Employee[5]; The above statement creates an array of five employee objects

  30. Sorting Arrays of Objects

  31. Using the Arrays Class • You can use arrays to store all kinds of objects.

  32. Two dimensional arrays Int[] [] someNumbers = new int[3][4]; Creates a two-dimensional array of ints with a total of 12 elements Int[] [] someNumbers = {{9,10,11,12}, {1,2,3,4}, {5,6,7,8}}; Creates and initializes a two-dimensional array of ints with 12 elements

  33. A two dimensional array • is also called a matrix or table • Can create even higher dimensional arrays

  34. That’s it

  35. import java.util.*; import javax.swing.*; public class ArraysDemo2 { public static void main(String[] args) { char[] grades = {'A', 'B', 'C', 'D', 'F'}; String entry; char myGrade; int position; entry = JOptionPane.showInputDialog(null, "Enter student grade"); myGrade= entry.charAt(0); position = Arrays.binarySearch(grades, myGrade); if(position >= 0) JOptionPane.showMessageDialog(null, "Position of " + myGrade + " is " + position); else JOptionPane.showMessageDialog(null, "Invalid grade"); System.exit(0); } }

  36. import javax.swing.*; public class FindDiscount { public static void main(String[] args) { final int NUM_RANGES = 5; int[] discountRangeLimit = { 1, 13, 50, 100, 200}; double[] discountRate = {0.00, 0.10, 0.14, 0.18, 0.20}; double customerDiscount; String strNumOrdered; int numOrdered; int sub = NUM_RANGES - 1; strNumOrdered = JOptionPane.showInputDialog(null, "How many items are ordered?"); numOrdered = Integer.parseInt(strNumOrdered); while(sub >= 0 && numOrdered < discountRangeLimit[sub]) --sub; customerDiscount = discountRate[sub]; JOptionPane.showMessageDialog(null, "Discount rate for " + numOrdered + " items is " + customerDiscount); System.exit(0); } • }

  37. public class PassArray { public static void main(String[] args) { final int NUM_ELEMENTS = 4; int[] someNums = {5, 10, 15, 20}; int x; System.out.print("At start of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x] ); System.out.println(); methodGetsArray(someNums, NUM_ELEMENTS); System.out.print("At end of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x]); System.out.println(); } public static void methodGetsArray(int arr[], int numEls) { int x; System.out.print("At start of method arr holds: "); for(x = 0; x < numEls; ++x) System.out.print(" " + arr[x] ); System.out.println(); for(x = 0; x < numEls; ++x) arr[x] = 888; System.out.print(" and at end of method arr holds: "); for(x = 0; x < numEls; ++x) System.out.print(" " + arr[x] ); System.out.println(); } • }

  38. import javax.swing.*; public class SearchList { public static void main(String[] args) { String[] deptName = {"Accounting", "Human Resources", "Sales"}; String dept; int x; boolean deptWasFound = false; dept = JOptionPane.showInputDialog(null, "Enter a department name"); for(x = 0; x < deptName.length; ++x) if(dept.equals(deptName[x])) deptWasFound = true; if(deptWasFound) JOptionPane.showMessageDialog(null, dept + " was found in the list"); else JOptionPane.showMessageDialog(null, dept + " was not found in the list"); System.exit(0); } }

  39. import java.util.*; public class ArraysDemo { public static void main(String[] args) { int[] myScores = new int[5]; display("Original array: ", myScores); Arrays.fill(myScores, 8); display("After filling with 8s: ", myScores); myScores[2] = 6; myScores[4] = 3; display("After changing two values: ", myScores); Arrays.sort(myScores); display("After sorting: ", myScores); } public static void display(String message, int[] array) { int sz = array.length; System.out.print(message); for(int x = 0; x < sz; ++x) System.out.print(array[x] + " "); System.out.println(); } }

  40. import javax.swing.*; public class FindPrice { public static void main(String[] args) { final int NUMBER_OF_ITEMS = 10; int[] validValues = {101, 108, 201, 213, 266, 304, 311, 409, 411, 412}; double[] prices = {0.29, 1.23, 3.50, 0.69, 6.79, 3.19, 0.99, 0.89, 1.26, 8.00}; String strItem; int itemOrdered; double itemPrice = 0.0; boolean validItem = false; strItem = JOptionPane.showInputDialog(null, "Enter the item number you want to order"); itemOrdered = Integer.parseInt(strItem); for (int x = 0; x < NUMBER_OF_ITEMS; ++x) { if(itemOrdered == validValues[x]) { validItem = true; itemPrice = prices[x]; } } if(validItem) JOptionPane.showMessageDialog(null, "The price for item " + itemOrdered + " is $" + itemPrice); else JOptionPane.showMessageDialog(null, "Sorry - invalid item entered"); System.exit(0); } • }

  41. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JHello7 extends JApplet implements ActionListener { JLabel greeting = new JLabel("Hello. Who are you?"); Font headlineFont = new Font("Helvetica", Font.BOLD, 36); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press me"); JLabel personalGreeting = new JLabel(""); Container con = getContentPane(); public void init() { greeting.setFont(headlineFont); personalGreeting.setFont(headlineFont); con.add(greeting); con.add(answer); con.add(pressMe); con.setLayout(new FlowLayout()); pressMe.addActionListener(this); answer.addActionListener(this); } public void actionPerformed(ActionEvent e) { String name = answer.getText(); personalGreeting.setText("Hello, " + name); con.add(personalGreeting); validate(); } • }

  42. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JHello8 extends JApplet implements ActionListener { JLabel greeting = new JLabel("Hello. Who are you?"); Font headlineFont = new Font("Helvetica", Font.BOLD, 36); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press me"); JLabel personalGreeting = new JLabel(""); Container con = getContentPane(); public void init() { greeting.setFont(headlineFont); personalGreeting.setFont(headlineFont); con.add(greeting); con.add(answer); con.add(pressMe); con.setLayout(new FlowLayout()); pressMe.addActionListener(this); answer.addActionListener(this); } public void actionPerformed(ActionEvent e) { remove(pressMe); remove(answer); String name = answer.getText(); personalGreeting.setText("Hello, " + name); con.add(personalGreeting); validate(); } }

  43. public class PassArrayElement { public static void main(String[] args) { final int NUM_ELEMENTS = 4; int[] someNums = {5, 10, 15, 20}; int x; System.out.print("At start of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x] ); System.out.println(); for(x = 0; x < NUM_ELEMENTS; ++x) methodGetsOneInt(someNums[x]); System.out.print("At end of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x]); System.out.println(); } public static void methodGetsOneInt(int one) { System.out.print("At start of method one is: " + one); one = 999; System.out.println(" and at end of method one is: " + one); } }

More Related