Download presentation
Presentation is loading. Please wait.
Published byMatthew Merritt Modified over 9 years ago
1
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
2
Method Overloading Method overloading is the process of giving a single method name multiple definitions in a class If a method is overloaded, the method name is not sufficient to determine which method is being called The signature of each overloaded method must be unique The signature includes the number, type, and order of the parameters Copyright © 2012 Pearson Education, Inc.
3
Method Overloading The indexOf method of String class is overloaded Copyright © 2012 Pearson Education, Inc. int indexOf(char ch) Returns the index of the first occurrence of char ch in this string. Returns -1 if not matched. int indexOf(char ch, int fromIndex) Returns the index of the first occurrence of char ch in this string after fromIndex. Returns -1 if not matched. int indexOf(String s) Returns the index of the first occurrence of String cs in this string. Returns -1 if not matched. int indexOf(String s, int fromIndex) Returns the index of the first occurrence of String s in this string after fromIndex. Returns -1 if not matched.
4
Method Overloading The abs method of Math class is overloaded Copyright © 2012 Pearson Education, Inc. double abs(double d) float abs(float f) int abs(int i) long abs(long l)
5
Method Overloading The compiler determines which method is being invoked by analyzing the parameters float tryMe(int x) { return x +.375; } float tryMe(int x, float y) { return x*y; } result = tryMe(25, 4.32) Invocation Copyright © 2012 Pearson Education, Inc.
6
Overloading Methods The return type of the method is not part of the signature. That is, overloaded methods cannot differ only by their return type Constructors can be overloaded Overloaded constructors provide multiple ways to initialize a new object –Recall PrintWriter constructors Copyright © 2012 Pearson Education, Inc.
7
Overloading Example See MyMaxOverloaded.java MyMaxOverloaded.java Copyright © 2012 Pearson Education, Inc.
8
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
9
System.out.printf ("format string", data) The PrintWriter class has a printf method compatible with the fprintf method in C or Matlab. In the format string you can use format specifiers as well as leading text for the data you want to print. There should be exactly one data for each format specifier other than %n Copyright © 2012 Pearson Education, Inc.
10
Common Format Specifiers %d for integers %f for floating-point numbers %e for floating-point numbers (scientific notation) %s for string %c for char %b for boolean %n to advance to next line Copyright © 2012 Pearson Education, Inc.
11
Additional characters for format specifiers First of all, you can specify the length of data. If data doesn't fit, the space reserved is extended. Otherwise, numbers are aligned right, and strings are aligned left. To override this, you can additionally use a minus character. For numbers you can use zero character to fill the gap with 0's instead of blanks. For floating-point numbers you can use.digit to specify decimal places to digit. See Example_printf.javaExample_printf.java Copyright © 2012 Pearson Education, Inc.
12
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
13
Arrays Let’s say we need to hold the temperature values of each day in Ankara in the past year Hard way: Create 365 different variables to hold each day’s temperature double tempDay1, tempDay2, …, …,tempDay365; Ughhhhh!!! Very difficult to even declare, use and manipulate! Easy way: use an array to hold all days temperatures Copyright © 2012 Pearson Education, Inc.
14
How to Declare an Array Create an array variable called temperatures Declared as follows : double[] temperatures = new double[365 ]; This sets up a location in memory for 365 double variables at once Copyright © 2012 Pearson Education, Inc.
15
Arrays Key Features Arrays provide an easy way to hold related variables at once (for example, temperature for the past year, gas prices for the last 30 days) It has some ordering, we can refer to array elements based on that ordering Homogenous, all data within a single array must share the same data type (for example, you can create an array of integer or boolean values, but not both) The size of an array is fixed once it is created. Copyright © 2012 Pearson Education, Inc.
16
Array Elements Type The element type can be a primitive type or an object reference Therefore, we can create an array of integers, an array of characters, an array of boolean, an array of String objects Copyright © 2012 Pearson Education, Inc.
17
Declaring Arrays First you declare an array reference variable int [] myFirstArray; //declares an array //variable for ints Then you instantiate the array, that is allocate the necessary amount of memory for the array and let the variable hold the starting address of the array. myFirstArray = new int [10]; //allocates memory We can combine the declaration and instantiation lines into one line as follows: int [] myFirstArray = new int [10];
18
Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; The type is int (an array of integers) The name of the array is scores The size of the array is 10 All positions of the new array will automatically be initialized to the default value for the array’s type. Copyright © 2012 Pearson Education, Inc. 0 0 0 0 0 0 0 0 0 0
19
Declaring Arrays 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]; Copyright © 2012 Pearson Education, Inc.
20
Arrays are Objects In Java, the array itself is an object that must be instantiated Another way to depict the scores array: scores 79 87 94 82 67 98 87 81 74 91 Copyright © 2012 Pearson Education, Inc. The name of the array is an object reference variable
21
Array Basics Array1.java Copyright © 2012 Pearson Education, Inc.
22
Array Elements Refers to the individual items represented by the array. For example, –an array of 10 integers is said to have 10 elements –an array of 5 characters has 5 elements –and so on…
23
Array Index Refers to one particular element’s position number in the array or more formally, as a subscript int[] scores = new int[10]; Copyright © 2012 Pearson Education, Inc. 0 1 2 3 4 5 6 7 8 9 89 91 84 62 67 98 87 81 74 91 An array of size N is indexed from 0 (zero) to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9
24
Array Element A particular value in an array is referenced using the array name followed by the index in brackets scores[2] refers to the value 94 (the 3rd value in the array) Copyright © 2012 Pearson Education, Inc. 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91
25
BasicArray.java The following example demonstrates the use of indices. See BasicArray.java BasicArray.java Copyright © 2012 Pearson Education, Inc.
26
Arrays An array element can be assigned a value, printed, or used in a calculation : scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); Copyright © 2012 Pearson Education, Inc. See Array2.java Array2.java
27
Array Naming Considerations The rules for naming variables apply when selecting array variable names –Composed of letter, digit, $ and underscore characters –Cannot start with a digit –Begins with a smallcase letter by convention Copyright © 2012 Pearson Education, Inc.
28
Array Length and Bounds Once an array is created, it has a fixed size An index used in an array reference must specify a valid element. That is, if the array length is N, the index value must be in range 0 to N-1 You will get the run-time error, ArrayIndexOutOfBoundsException if you use an invalid index Copyright © 2012 Pearson Education, Inc.
29
Bounds Checking For example, if the array codes can hold 100 values, it can be indexed from 0 to 99 It’s common to introduce off-by-one errors when using arrays: for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem Copyright © 2012 Pearson Education, Inc.
30
Array Length Each array object has a public constant (not a method) called length that stores the size of the array It is referenced using the array name: scores.length length holds the number of elements (not the largest index!) Length is not a method so there is no parenthesis at the end unlike String class length() method Copyright © 2012 Pearson Education, Inc.
31
Basic Array Examples Array3.java ReverseOrder.java Copyright © 2012 Pearson Education, Inc.
32
//******************************************************************** // 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
33
Copyright © 2012 Pearson Education, Inc. continue 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] + " "); System.out.println (); }
34
Copyright © 2012 Pearson Education, Inc. continue 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] + " "); } 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
35
Array Initializers An array initializer combines the declaration, creation, and initialization of an array in one statement using the following syntax: elementType [] arrayReferenceVariable = {value0, value1,..., valueK}; Copyright © 2012 Pearson Education, Inc.
36
Initializer Lists An initializer list can be used to instantiate and fill an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] grades = {'A', 'B', 'C', 'D', ’F'}; Copyright © 2012 Pearson Education, Inc.
37
Initializer Lists Note that when an initializer list is used: –the new operator is not used –no size value is specified The size of the array is determined by the number of items in the list An initializer list can be used only in the array declaration See Primes.javaPrimes.java Copyright © 2012 Pearson Education, Inc.
38
//******************************************************************** // Primes.java Author: Lewis/Loftus // // Demonstrates the use of an initializer list for an array. //******************************************************************** public class Primes { //----------------------------------------------------------------- // Stores some prime numbers in an array and prints them. //----------------------------------------------------------------- public static void main (String[] args) { int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length); System.out.println ("The first few prime numbers are:"); for(int i=0; i < primeNums.length; i++){ System.out.print (primeNums[i] + " "); }
39
Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Primes.java Author: Lewis/Loftus // // Demonstrates the use of an initializer list for an array. //******************************************************************** public class Primes { //----------------------------------------------------------------- // Stores some prime numbers in an array and prints them. //----------------------------------------------------------------- public static void main (String[] args) { int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length); System.out.println ("The first few prime numbers are:"); for(int i=0; i < primeNums.length; i++){ System.out.print (primeNums[i] + " "); } Output Array length: 8 The first few prime numbers are: 2 3 5 7 11 13 17 19
40
Example: Find the frequency of the result of throwing a dice 6000 times See RollDice.java RollDice.java Copyright © 2012 Pearson Education, Inc.
41
for-each loops for-each loop (enhanced for loop) enables you to traverse the array sequentially without using an index variable for (double d: array) System.out.println(d); is equivalent to for (int i = 0; i < array.length; i++){ double d = array [i]; System.out.println(d); } Copyright © 2012 Pearson Education, Inc.
42
Another example int sum = 0; int[] list = {1, 2, 3}; for (int value : list){ sum += value; } Copyright © 2012 Pearson Education, Inc. sum list value 0 123 1
43
Another example int sum = 0; int[] list = {1, 2, 3}; for (int value : list){ sum += value; } Copyright © 2012 Pearson Education, Inc. sum list value 1 123 2
44
Another example int sum = 0; int[] list = {1, 2, 3}; for (int value : list){ sum += value; } Copyright © 2012 Pearson Education, Inc. sum list value 3 123 3
45
Another example int sum = 0; int[] list = {1, 2, 3}; for (int value : list){ sum += value; } Copyright © 2012 Pearson Education, Inc. sum list 6 123
46
Example InitializerList.java demonstrates the usage of array initializers and for-each loops.InitializerList.java Copyright © 2012 Pearson Education, Inc.
47
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
48
Arrays of Objects The elements of an array can be object references The following declaration reserves space to store 5 references to String objects String[] array = new String[5]; It does NOT create the String objects themselves Initially an array of objects holds null references Each object stored in an array must be instantiated separately Copyright © 2012 Pearson Education, Inc.
49
Arrays of Objects The array array when initially declared: At this point, the following line of code would throw a NullPointerException : System.out.println(array[0].length() ); See ArrayOfStrings.java ArrayOfStrings.java array - - - - - Copyright © 2012 Pearson Education, Inc.
50
Arrays of Objects Keep in mind that String objects can be created using literals The following declaration creates an array object called verbs and fills it with five String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep", "run"}; See StringArr.javaStringArr.java Copyright © 2012 Pearson Education, Inc.
51
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
52
Arrays as Parameters An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Therefore, changing an array element within the method changes the original An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type Copyright © 2012 Pearson Education, Inc.
53
Examples of Array as Parameters Array4.java MakeHot.java ArrParametersAndReturns.java Copyright © 2012 Pearson Education, Inc.
54
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
55
Variable Length Parameter Lists Suppose we wanted to create a method that processed a different amount of data from one invocation to the next For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75); Copyright © 2012 Pearson Education, Inc.
56
Variable Length Parameter Lists Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method public double average (int... list) { // whatever } element type array name Indicates a variable length parameter list Copyright © 2012 Pearson Education, Inc.
57
Variable Length Parameter Lists Copyright © 2012 Pearson Education, Inc. public double average (int... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list){ sum += num; } result = (double)sum / list.length; } return result; }
58
Example See VarArgsDemo.javaVarArgsDemo.java Copyright © 2012 Pearson Education, Inc.
59
Example Copyright © 2012 Pearson Education, Inc. Write method called distance that accepts a variable number of doubles (which each represent the distance of one leg of a trip) and returns the total distance of the trip. See Trip.java Trip.java
60
Variable Length Parameter Lists A method that accepts a variable number of parameters can also accept other parameters, but variable number of parameters can exist only once and as the last parameter The following method accepts an int, a String object, and a variable number of double values into an array called nums public void test (int count, String name, double... nums) { // whatever } Copyright © 2012 Pearson Education, Inc.
61
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
62
split() Method from String Class public String[] split(String delimiter) Method takes a String delimiter Returns a String array The split method in the String class returns an array of strings consisting of the substrings split by the delimiters. Copyright © 2012 Pearson Education, Inc. Aaa bbb ccc String str = "Aaa, bbb, ccc"; String[] arr = str.split(", "); arr = delimiter
63
Examples: String str = "Java#HTML#Perl“; String [] tokens = str.split("#"); for (String token: tokens) System.out.println (token.toUpperCase()); Copyright © 2012 Pearson Education, Inc.
64
Examples: String str = “Java#HTML#Perl”; String [] tokens = str.split("#"); for (String token: tokens) System.out.println (token.toUpperCase()); Generates the following output: JAVA HTML PERL Copyright © 2012 Pearson Education, Inc.
65
Examples: String str = "HiHow are you?"; String [] tokens = str.split("\t"); for (int i=0; i < tokens.length; i++) System.out.println (tokens[i]); Copyright © 2012 Pearson Education, Inc.
66
Examples: String str = "HiHow are you?"; String [] tokens = str.split("\t"); for (int i=0; i < tokens.length; i++) System.out.println (tokens[i]); Generates the following output: Hi How are you? Copyright © 2012 Pearson Education, Inc.
67
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
68
Wrapper Classes A wrapper class represents a particular primitive type as an object. For example, Integer class represents a simple integer value. An Integer object may be created as Integer obj = new Integer(40); All wrapper classes are in the java.lang package (no need to import). Copyright © 2012 Pearson Education, Inc.
69
Wrapper Classes in the java.lang Package Primitive typeWrapper class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid Copyright © 2012 Pearson Education, Inc.
70
Integer Class Useful methods from the Integer class: Integer (int value) : creates an Integer object storing the specified value Integer (String str) : creates an Integer object storing the integer value extracted from the string, str static int parseInt(String str) : returns the int corresponding to the value stored in the specified string, str static String toBinaryString(int num) : returns a string representation of the specified integer value in base 2 static String toString(int num) : returns a string representation of the specified integer value in base 10 static Integer valueOf(String str) : returns a Integer object holding the int value represented by the argument string str. Constants from the Integer class: Integer.MIN_VALUE returns the minimum int value, -2 31 Integer.MAX_VALUE returns the maximum int value, 2 31 -1 Copyright © 2012 Pearson Education, Inc.
71
Double Class Some methods from the Double class: Double (double value) : creates a Double object storing the specified value Double (String str) : creates a Double object storing the double value in string, str static double parseDouble(String str) : returns the double corresponding to the value stored in the specified string, str static String toString(double num) : returns a string representation of the specified double value static Double valueOf(String str) : returns a Double object holding the double value represented by the argument string str. Constants from the Double class: Double.MIN_VALUE returns the minimum double value Double.MAX_VALUE returns the maximum double value Copyright © 2012 Pearson Education, Inc.
72
Example for split() and reading from a text file See WrapperSplitFile.java WrapperSplitFile.java Copyright © 2012 Pearson Education, Inc.
73
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper Classes Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc.
74
Two-Dimensional Arrays A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions Copyright © 2012 Pearson Education, Inc.
75
Two-Dimensional Arrays To be precise, in Java a two-dimensional array is an array of arrays A two-dimensional array is declared by specifying the size of each dimension separately: int[][] table = new int[12][50]; A array element is referenced using two index values: value = table[3][6] The array stored in one row can be specified using one index Copyright © 2012 Pearson Education, Inc.
76
Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc. ExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] array of integers table[5][12]int integer
77
Two-Dimensional Arrays int[][] matrix = new int[2][7]; //creates a 2-by-7 array matrix[0][2] = 5; Copyright © 2012 Pearson Education, Inc. 0000000 0000000 00 50000 00 00000
78
Multidimensional Arrays You can think of it as array of arrays for (int i=0; i < 2; i++){ for (int j=0; j<7; j++){ matrix[i][j]=1; } Copyright © 2012 Pearson Education, Inc. 1 1 1 1 1 1 1 1 1 1 1 1 1 1
79
Two-Dimensional Arrays See TwoDArray.javaTwoDArray.java Copyright © 2012 Pearson Education, Inc.
80
//******************************************************************** // TwoDArray.java Author: Lewis/Loftus // // Demonstrates the use of a two-dimensional array. //******************************************************************** public class TwoDArray { //----------------------------------------------------------------- // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. //----------------------------------------------------------------- public static void main (String[] args) { int[][] table = new int[5][10]; // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table for (int row=0; row < table.length; row++) { for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); }
81
Copyright © 2012 Pearson Education, Inc. //******************************************************************** // TwoDArray.java Author: Lewis/Loftus // // Demonstrates the use of a two-dimensional array. //******************************************************************** public class TwoDArray { //----------------------------------------------------------------- // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. //----------------------------------------------------------------- public static void main (String[] args) { int[][] table = new int[5][10]; // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table for (int row=0; row < table.length; row++) { for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); } Output 0123456789 101112131415161718 19 202122232425262728 29 303132333435363738 39 404142434445464748 49
82
Example & Exercise See GradeExam.java GradeExam.java Exercise: Modify the code such that there are two methods: –gradeAStudent : grades one student –gradeAllStudents: grades all students Copyright © 2012 Pearson Education, Inc.
83
Example See FindNearestPoints.java FindNearestPoints.java Copyright © 2012 Pearson Education, Inc.
84
Two-Dimensional Arrays See SodaSurvey.javaSodaSurvey.java Copyright © 2012 Pearson Education, Inc.
85
//******************************************************************** // SodaSurvey.java Author: Lewis/Loftus // // Demonstrates the use of a two-dimensional array. //******************************************************************** import java.text.DecimalFormat; public class SodaSurvey { //----------------------------------------------------------------- // Determines and prints the average of each row (soda) and each // column (respondent) of the survey scores. //----------------------------------------------------------------- public static void main (String[] args) { int[][] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4}, {2, 4, 3, 4, 3, 3, 2, 1, 2, 2}, {3, 5, 4, 5, 5, 3, 2, 5, 5, 5}, {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} }; final int SODAS = scores.length; final int PEOPLE = scores[0].length; int[] sodaSum = new int[SODAS]; int[] personSum = new int[PEOPLE]; continue
86
Copyright © 2012 Pearson Education, Inc. continue for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) { sodaSum[soda] += scores[soda][person]; personSum[person] += scores[soda][person]; } DecimalFormat fmt = new DecimalFormat ("0.#"); System.out.println ("Averages:\n"); for (int soda=0; soda < SODAS; soda++) System.out.println ("Soda #" + (soda+1) + ": " + fmt.format ((float)sodaSum[soda]/PEOPLE)); System.out.println (); for (int person=0; person < PEOPLE; person++) System.out.println ("Person #" + (person+1) + ": " + fmt.format ((float)personSum[person]/SODAS)); }
87
Copyright © 2012 Pearson Education, Inc. continue for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) { sodaSum[soda] += scores[soda][person]; personSum[person] += scores[soda][person]; } DecimalFormat fmt = new DecimalFormat ("0.#"); System.out.println ("Averages:\n"); for (int soda=0; soda < SODAS; soda++) System.out.println ("Soda #" + (soda+1) + ": " + fmt.format ((float)sodaSum[soda]/PEOPLE)); System.out.println (); for (int person=0; person < PEOPLE; person++) System.out.println ("Person #" + (person+1) + ": " + fmt.format ((float)personSum[person]/SODAS)); } Output Averages: Soda #1: 3.2 Soda #2: 2.6 Soda #3: 4.2 Soda #4: 1.9 Person #1: 2.2 Person #2: 3.5 Person #3: 3.2 Person #4: 3.5 Person #5: 2.5 Person #6: 3 Person #7: 2 Person #8: 2.8 Person #9: 3.2 Person #10: 3.8
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.