AP Computer Science A - 10th Grade

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Encapsulate the Name class. Modify the existing code shown below to make its fields private, and add appropriate accessor methods to the class named getFirstName, getMiddleInitial, and getLastName.

// A Name object represents a person's name such as "John Q. Public". public class Name { private String firstName; private char middleInitial; private String lastName; public String getFirstName(){ return firstName; } public char getMiddleInitial(){ return middleInitial; } public String getLastName(){ return lastName; } public Name(String first, char middle, String last) { firstName = first; middleInitial = middle; lastName = last; } }

What are the benefits of encapsulation?

- Abstraction between object and clients - Protects object from unwanted access - Can change the class implementation later - Can constrain objects' state (invariants)

What are the two kinds of methods?

- Accessor (getters) - Mutator (setters)

Some problems that can be solved by traversing an array are...

- Comparing two arrays for equality. - Searching an array for a given value. - Printing an array's elements.

How can we see abstraction in an iPod?

- You understand its external behavior (buttons, screen). - You don't understand its inner details, and you don't need to.

How to transverse an array zig zag-ed right to left

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int rows = 0; rows < matrix.length; rows++) { for(int columns = matrix[rows].length-1; columns >= 0; columns--){ if (rows%2 == 0) { collapsed[counter] = matrix[rows][matrix[rows].length-1-columns]; }else{ collapsed[counter] = matrix[rows][columns]; } counter++; } }

Write code that creates an array of integers named data of size 5 with the following contents: 27, 51, 33, -1, 101

int[] data = new int[5]; data[0] = 27; data[1] = 51; data[2] = 33; data[3] = -1; data[4] = 101;

Write a piece of code that declares an array variable named data with the elements 7, -1, 13, 24, and 6. Use only one statement to initialize the array.

int[] data = {7, -1, 13, 24, 6};

Write code that creates an array named odds and stores all odd numbers between -6 and 38 into it using a for loop. Make the array's size exactly large enough to store the numbers.

int[] odds = new int[22]; for(int i = 0; i < 22; i++){ odds[i] = (i * 2) - 5; }

Write a piece of code that constructs a two-dimensional array of integers named table with 5 rows and 10 columns. Fill the array with a multiplication table, so that array element [i][j] contains the value i * j. Use nested for loops to build the array.

int[][] table = new int[5][10]; for(int i = 0; i < table.length; i++){ for(int j = 0; j < table[i].length; j++){ table[i][j] = i *j; } }

Add a constructor to the Name class that accepts a first name, middle initial, and last name as parameters (in that order) and initializes the Name object's state with those values.

public Name (String firstName, char middleInitial, String lastName){ this.firstName = firstName; this.lastName = lastName; this.middleInitial = middleInitial; }

Define shadowing

2 variables with same name in same scope. Normally illegal, except when one variable is a field.

What does encapsulation force?

Abstraction - Separates external view (behavior) from internal view (state) - Protects the integrity of an object's data

Add a constructor to the Point class that accepts another Point as a parameter and initializes the new Point to have the same (x, y) values. Use the keyword this in your solution. Recall that your code is being added to the following class: public class Point { int x; int y; // // your code goes here }

public Point(Point point1){ this.x = point1.x; this.y = point1.y; }

The following constructor has two major problems. What are they? Find and fix the problems, and submit a working version of the code. Recall that your code is being added to the following class: public class Point { int x; int y; // // your code goes here }

public Point(int initialX, int initialY) { this.x = initialX; this.y = initialY; }

What are some synonyms for state?

Field, instance variables, state fields.

Define encapsulation

Hiding implementation details from clients.

What does Java do if a class does not have a constructor?

If a class has no constructor, Java gives it a default constructor with no parameters that sets all fields to 0.

Define constructor

Initializes the state of new objects.

Define behavior

Methods you can call to update the state.

What are the behaviors for the Point class?

Methods.

What are the states and behaviors of an iPod?

State: - current song - volume - battery life Behavior: - power on/off - change station/song - change volume - choose random song

What is object oriented programing (OOP)?

Programs that perform their behavior as interactions between objects.

Define this

Refers to the implicit parameter inside your class. (a variable that stores the object on which a method is called)

When are constructors called?

Runs when the client uses the new keyword or is called by another constructor (this).

Write code that uses a for loop to print each element of an array named data that contains five integers. If the array contains the elements [14, 5, 27, -3, 2598], then your code should produce the following output: element [0] is 14 element [1] is 5 element [2] is 27 element [3] is -3 element [4] is 2598

for(int i = 0; i < data.length; i++){ System.out.println("element ["+i+"] is "+data[i]); }

Assume that a two-dimensional rectangular array of integers called matrix has been declared with six rows and eight columns. Write a for loop to copy the contents of the second column into the fifth column.

for(int i = 0; i < matrix.length; i++){ matrix[i][4] = matrix[i][1]; }

Assume that a two-dimensional rectangular array of integers called data has been declared with four rows and seven columns. Write a for loop to initialize the third row of data to store the numbers 1 through 7.

for(int i = 0; i<data[2].length; i++){ data[2][i] = i+1; }

How to transverse an array left to right

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int rows = 0; rows < matrix.length; rows++) { for(int columns = 0; columns < matrix[rows].length; columns++){ collapsed[counter] = matrix[rows][columns]; counter++; } }

How to transverse an array right to left

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int rows = 0; rows < matrix.length; rows++) { for(int columns = matrix[rows].length-1; columns >= 0; columns--){ collapsed[counter] = matrix[rows][columns]; counter++; } }

Why does a method to swap two array elements work correctly when a method to swap two integer values does not?

Unlike integers, arrays are objects and use reference semantics.

What happens when you override an object class?

You replace what it does.

Create a toString method which formats a Point object as (x, y).

@Override public String toString(){ return "("+ x + ", "+ y + ")"; }

What happens to the default parameter when you make your own?

A default constructor is deleted when you create your own constructor with parameter.

Define abstraction

A distancing between ideas and details. We can use objects without knowing how they work.

Define private field

A field that cannot be accessed from outside the class.

Define accessor class

A method that lets clients examine object state. - Often has a non-void return type

Define mutator class

A method that modifies an object's state. - Often has a void return type,

Define class

A program entity that represents either: - A program / module, or - A template for a new type of objects.

An array transversal is...

A sequential processing of each of an array's elements.

Define object

An entity that combines state and behavior.

What is an example of an integrated Java class?

The DrawingPanel class is a template for creating DrawingPanel objects.

What is the "blueprint"?

The class (blueprint) will describe how to create objects.

Define state

To store the data of an object.

What is an example of an accessor method?

distance, distanceFromOrigin

Write a method called equals that takes in two string arrays and returns true if they are equal; that is, if both arrays have the same length and contain equivalent string values at each index.

import java.util.Arrays; public static boolean equals (String[] stringArray1, String[] stringArray2){ return(Arrays.equals(stringArray1,stringArray2)); }

Syntax to declare an array of 10 integers

int[] a = new int[10];

Syntax for quickly declaring/initializing an array of six integers to store a particular list of values?

int[] a = {17, -3, 42, 5, 9, 28};

How to transverse an array top to bottom

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int columns = 0; columns < matrix[matrix.length-1].length; columns++) { for(int rows = 0; rows < matrix.length; rows++){ collapsed[counter] = matrix[rows][columns]; counter++; } }

How to transverse an array bottom to top

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int columns = 0; columns < matrix[matrix.length-1].length; columns++) { for(int rows = matrix.length-1; rows >= 0; rows--){ collapsed[counter] = matrix[rows][columns]; counter++; } }

How to transverse an array zig zag-ed top to bottom

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int columns = 0; columns < matrix[matrix.length-1].length; columns++) { if (counter % matrix.length == 0) { for(int rows = 0; rows < matrix.length; rows++){ collapsed[counter] = matrix[rows][columns]; counter++; } }else{ for(int rows = matrix.length-1; rows >= 0; rows--){ collapsed[counter] = matrix[rows][columns]; counter++; } } }

How to transverse an array zig zag-ed bottom to top

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int columns = 0; columns < matrix[matrix.length-1].length; columns++) { if (counter % matrix.length == 0) { for(int rows = matrix.length-1; rows >= 0; rows--){ collapsed[counter] = matrix[rows][columns]; counter++; } }else{ for(int rows = 0; rows < matrix.length; rows++){ collapsed[counter] = matrix[rows][columns]; counter++; } } }

How to transverse an array zig zag-ed left to right

int[] collapsed = new int[matrix.length*matrix[0].length]; int counter = 0; for(int rows = 0; rows < matrix.length; rows++) { for(int columns = 0; columns < matrix[rows].length-1; columns++){ if (rows%2 == 0) { collapsed[counter] = matrix[rows][matrix[rows].length-1-columns]; }else{ collapsed[counter] = matrix[rows][columns]; }counter++; } }

Syntax to access the first element of an array

numbers[0]

Syntax to access the last element of an array

numbers[numbers.length-1]

Add two new methods to the Name class: public String getNormalOrder() Returns the person's name in normal order, with the first name followed by the middle initial and last name. For example, if the first name is "John", the middle initial is 'Q', and the last name is "Public", this method returns "John Q. Public". public String getReverseOrder() Returns the person's name in reverse order, with the last name preceding the first name and middle initial. For example, if the first name is "John", the middle initial is 'Q', and the last name is "Public", this method returns "Public, John Q.". (You don't need to write the class header or declare the fields; assume that this is already done for you. Just write your two methods' complete code in the box provided.)

public String getNormalOrder(){ return firstName +" "+ middleInitial +". "+ lastName; } public String getReverseOrder(){ return lastName +", "+ firstName +" "+ middleInitial+"."; }

Add the following method to the Point class: public String toString() Make it return a string in the following format. For example, if a Point object stored in a variable pt represents the point (5, -17), return the string: java.awt.Point[x=5,y=-17]

public String toString(){ return "java.awt.Point[x="+x+",y="+y+"]"; }

Write a toString method for the Name class that returns a String such as "John Q. Public".

public String toString(){ return firstName+" "+middleInitial+". "+lastName; }

Create a class called Name that represents a person's name. The class should have fields named firstName representing the person's first name, lastName representing their last name, and middleInitial representing their middle initial (a single character). Your class should contain only fields for now.

public class Name { String firstName; String lastName; char middleInitial; }

Add the following method to the Point class: public double distance(Point other) Returns the distance between the current Point object and the given other Point object. The distance between two points is equal to the square root of the sum of the squares of the differences of their x- and y-coordinates. In other words, the distance between two points (x1, y1) and (x2, y2) can be expressed as the square root of (x2 - x1)2 + (y2 - y1)2. Two points with the same (x, y) coordinates should return a distance of 0.0.

public double distance(Point other){ int dx = x - other.x; int dy = y - other.y; return Math.sqrt((Math.pow(dx, 2))+(Math.pow(dy, 2))); }

Add the following method to the Point class: public int quadrant() Returns which quadrant of the x/y plane this Point object falls in. Quadrant 1 contains all points whose x and y values are both positive. Quadrant 2 contains all points with negative x but positive y. Quadrant 3 contains all points with negative x and y values. Quadrant 4 contains all points with positive x but negative y. If the point lies directly on the x and/or y axis, return 0. public class Point { private int x; private int y; // // your code goes here }

public int quadrant(){ if (x > 0 && y > 0){ return 1; } else if (x < 0 && y > 0){ return 2; } else if (x < 0 && y < 0){ return 3; } else if (x > 0 && y < 0){ return 4; } else{ return 0; } }

Add methods named setX and setY to the Point class. Each method accepts an integer parameter and changes the Point object's x- or y-coordinate to be the value passed, respectively. Your code is being added to the following class: public class Point { int x; int y; // // your code goes here }

public int setX(int swap){ this.x = swap; return x; } public int setY(int swap){ this.y = swap; return y; }

Write a method called allLess that accepts two arrays of integers and returns true if each element in the first array is less than the element at the same index in the second array.

public static boolean allLess(int[] array1, int[] array2){ if (array1.length != array2.length){ return false; } int lessThan = 0; for(int i = 0; i< array1.length; i++){ if (array1[i]<array2[i]){ lessThan++; } } return lessThan==array2.length; }

Write a static method named contains that accepts two arrays of integers a1 and a2 as parameters and that returns a boolean value indicating whether or not a2's sequence of elements appears in a1 (true for yes, false for no). The sequence of elements in a2 may appear anywhere in a1 but must appear consecutively and in the same order.

public static boolean contains (int[] list1, int[] list2){ for(int i = 0; i<list1.length; i++){ if (Arrays.equals((Arrays.copyOfRange(list1, i, i+list2.length)), list2)){ return true; } } return false; }

Write a method isPalindrome that accepts an array of Strings as its argument and returns true if that array is a palindrome (if it reads the same forwards as backwards) and false if not. For example, the array {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} is a palindrome, so passing that array to your method would return true. Arrays with zero or one element are considered to be palindromes.

public static boolean isPalindrome (String[] array){ int palindrome = 0; for (int i = 0; i<array.length/2; i++){ if (array[0 + i] == array [(array.length-1)-i]){ palindrome++; } } return (palindrome == array.length/2); }

Write a static method named isSorted that accepts an array of doubles as a parameter and returns true if the list is in sorted (nondecreasing) order and false otherwise. For example, if arrays named list1 and list2 store {16.1, 12.3, 22.2, 14.4} and {1.5, 4.3, 7.0, 19.5, 25.1, 46.2} respectively, the calls isSorted(list1) and isSorted(list2) should return false and true respectively. Assume the array has at least one element. A one-element array is considered to be sorted.

public static boolean isSorted(double[] list) { for(int i = 0; i < list.length - 1; i++) { if(list[i + 1] < list[i]){ return false; } } return true; }

Write a method named isUnique that takes an array of integers as a parameter and that returns a boolean value indicating whether or not the values in the array are unique (true for yes, false for no). The values in the list are considered unique if there is no pair of values that are equal.

public static boolean isUnique(int[] a){ int unique = 0; for(int i = 0; i<a.length; i++){ for(int x = 0; x<a.length; x++){ if (a[i] == a[x]){ unique++; } } } return (unique == a.length); }

Write a method called average that computes the average (arithmetic mean) of all elements in an array of integers and returns the answer as a double. For example, if the array passed contains the values [1, -2, 4, -4, 9, -6, 16, -8, 25, -10], the calculated average should be 2.5. Your method accepts an array of integers as its parameter and returns the average. You may assume that the array contains at least one element. Your method should not modify the elements of the array.

public static double average(int[] a) { double sum = 0; for(int i = 0; i<a.length; i++){ sum += a[i]; } return sum/a.length; }

Write a method averageLength of code that computes and returns the average String length of the elements of an array of Strings. For example, if the array contains {"belt", "hat", "jelly", "bubble gum"}, the average length returned should be 5.5. Assume that the array has at least one element.

public static double averageLength (String [] array){ double sum = 0; for(int i = 0; i< array.length ;i++){ sum += array[i].length(); } return sum/array.length; }

Write a method called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements {6, 2, 9, 11, 3}, then your method should return 40.0. If the array contains no even elements or no elements at all, return 0.0.

public static double percentEven (int[] a){ double total = 0; double even = 0; for(int i = 0; i<a.length; i++){ if (a[i] % 2 == 0){ even++; } total++; } if (a.length == 0){ return 0.0; } else{ return ((even/total)*100); } }

Write a method called stdev that returns the standard deviation of an array of integers. Standard deviation is computed by taking the square root of the sum of the squares of the differences between each element and the mean, divided by one less than the number of elements. (It's just that simple!)

public static double stdev(int[] a) { double sum = 0; for(int i = 0; i<a.length; i++){ sum += a[i]; } double average = sum/a.length; double squaredAverage = 0; for(int i = 0; i<a.length; i++){ squaredAverage += Math.pow((a[i]-average),2); } return Math.sqrt(squaredAverage/(a.length-1)); }

Write a method called countInRange that accepts an array of integers, a minimum value, and a maximum value as parameters and returns the count of how many elements from the array fall between the minimum and maximum (inclusive).

public static int countInRange(int[] a, int min, int max) { int count = 0; for(int i = 0; i < a.length; i++){ if (a[i] <= max && a[i] >= min){ count++; } } return count; }

Write a method countStrings that takes an array of Strings and a target String and returns the number of occurences target appears in the array.

public static int countStrings (String[] arrayOfStrings, String targetString){ int numOfOccurences = 0; for(int i = 0; i<arrayOfStrings.length; i++){ if (arrayOfStrings[i].equals(targetString)){ numOfOccurences++; } } return numOfOccurences; }

Write a method called kthLargest that accepts an integer k and an array a as its parameters and returns the element such that k elements have greater or equal value. If k = 0, return the largest element; if k = 1, return the second largest element, and so on.

public static int kthLargest(int k, int[] a) { Arrays.sort(a); return a[a.length-(k+1)]; }

Write a method named lastIndexOf that accepts an array of integers and an integer value as its parameters and returns the last index at which the value occurs in the array. The method should return -1 if the value is not found. For example, in the list containing {74, 85, 102, 99, 101, 85, 56}, the last index of the value 85 is 5.

public static int lastIndexOf(int[] a, int target) { int found = -5; for(int i = 0; i < a.length; i++){ if(a[i]==target){ found = i; } } if (found==-5){ return -1; } else{ return found; } }

Write a method named longestSortedSequence that accepts an array of integers as a parameter and that returns the length of the longest sorted (nondecreasing) sequence of integers in the array.

public static int longestSortedSequence (int[] a){ int longest = 1; int count = 1; for(int i = 1; i<a.length;i++){ if (a[i-1] <= a[i]){ count++; } else{ if (count > longest){ longest = count; } count = 1; } } if (a.length==0){ return 0; } else{ return Math.max(longest, count); } }

Write a method called max that accepts an array of integers as a parameter and returns the maximum value in the array. For example, if the array passed stores {12, 7, -1, 25, 3, 9}, your method should return 25. You may assume that the array contains at least one element. Your method should not modify the elements of the array.

public static int max(int[] data) { int max = data[0]; for(int i = 1; i<data.length; i++){ if (data[i] > max){ max = data[i]; } } return max; }

Write a method called median that accepts an array of integers as its argument and returns the median of the numbers in the array. The median is the number that will appear in the middle if you arrange the elements in order. Assume that the array is of odd size (so that one sole element constitutes the median) and that the numbers in the array are between 0 and 99 inclusive.

public static int median (int[] a){ Arrays.sort(a); return a[a.length/2]; }

Write a method named minGap that accepts an integer array as a parameter and returns the minimum 'gap' between adjacent values in the array. The gap between two adjacent values in a array is defined as the second value minus the first value.

public static int minGap(int[] a) { int min = Integer.MAX_VALUE; for(int i = 0; i<a.length-1; i++){ if((a[i+1] - a[i])< min) min = a[i+1] - a[i]; } if (a.length<2){ return 0; } else{ return min; } }

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value.

public static int mode(int[] a) { int[] tallyArray = new int[101]; for(int i = 0; i < a.length; i++){ tallyArray[a[i]]++; } int mode = 101; int max = 0; for (int i = 0; i < tallyArray.length; i++) { if (tallyArray[i] > max) { max = tallyArray[i]; mode = i; } } return mode; }

Write a method priceIsRight that accepts an array of integers bids and an integer price as parameters. The method returns the element in the bids array that is closest in value to price without being larger than price.

public static int priceIsRight(int[] bids, int price){ int bigger = -1; for(int i = 0; i<bids.length; i++){ if (price - bids[i] >= 0 && bigger < bids[i]){ bigger = bids[i]; } } return bigger; }

Write a static method named range that takes an array of integers as a parameter and returns the range of values contained in the array. The range of an array is defined to be one more than the difference between its largest and smallest element. For example, if the largest element in the array is 15 and the smallest is 4, the range is 12. If the largest and smallest values are the same, the range is 1.

public static int range(int[] a) { int min = a[0]; int max = a[0]; for(int i = 1; i<a.length; i++){ if (a[i]<= min){ min = a[i]; } if (a[i]>= max){ max = a[i]; } } return (max-min) + 1; }

Write a method called append that accepts two integer arrays as parameters and returns a new array that contains the result of appending the second array's values at the end of the first array.

public static int[] append (int[] list1, int[] list2){ int[] conglomerateArray = new int[list1.length+list2.length]; int i = 0; for (int x = 0; x<list1.length; x++){ conglomerateArray[i]=list1[x]; i++; } for (int y = 0; y<list2.length; y++){ conglomerateArray[i]=list2[y]; i++; } return conglomerateArray; }

Write a method called collapse that accepts an array of integers as a parameter and returns a new array containing the result of replacing each pair of integers with the sum of that pair.

public static int[] collapse (int[] a){ int[] collapsedArray; if (a.length%2 == 0){ collapsedArray = new int[a.length/2]; } else{ collapsedArray = new int[(a.length/2)+1]; collapsedArray[(a.length) / 2] = a[a.length - 1]; } int counter = 0; for(int i = 0; i<a.length-1; i+=2){ collapsedArray[counter] = a[i] + a[i + 1]; counter++; } return collapsedArray; }

Write a static method named vowelCount that accepts a String as a parameter and returns an array of integers representing the counts of each vowel in the String. The array returned by your method should hold 5 elements: the first is the count of As, the second is the count of Es, the third Is, the fourth Os, and the fifth Us. Assume that the string contains no uppercase letters.

public static int[] vowelCount (String phrase){ int[] vowelTally = new int[5]; for(int i = 0; i<phrase.length(); i++){ char letter = phrase.charAt(i); if (letter == 'a'){ vowelTally[0]++; } if (letter == 'e'){ vowelTally[1]++; } if (letter == 'i'){ vowelTally[2]++; } if (letter == 'o'){ vowelTally[3]++; } if (letter == 'u'){ vowelTally[4]++; } } return vowelTally; }

The PointClient program is supposed to construct two Point objects, translate each, and then print their coordinates. The expected output is shown below. Finish the program so that it runs properly. p1 is (8, 2) p2 is (4, 3) p1's distance from origin is 8.246211251235321 p1 is now (9, 4) p2 is now (3, 13)

public static void main(String[] args) { // construct two Point objects, one at (8, 2) and one at (4, 3) Point p1 = new Point(8, 2); Point p2 = new Point(4, 3); // display the two Point objects' state System.out.println("p1 is ("+p1.x+", "+p1.y+")"); System.out.println("p2 is ("+p2.x+", "+p2.y+")"); // display p1 distance from origin System.out.println("p1's distance from origin is "+p1.distanceFromOrigin()); // translate p1 to (9, 4) p1.translate(1, 2); // translate p2 to (3, 13) p2.translate(-1, 10); // display the two Point objects' state again System.out.println("p1 is now ("+p1.x+", "+p1.y+")"); System.out.println("p2 is now ("+p2.x+", "+p2.y+")"); }

Write a method printBackwards that prints an array of integers in reverse order, in the following format.

public static void printBackwards(int[] data){ for(int i = data.length - 1; i>=0; i--){ System.out.println("element ["+i+"] is "+data[i]); } }

Write a method named swapPairs that accepts an array of strings as a parameter and switches the order of values in a pairwise fashion. Your method should switch the order of the first two values, then switch the order of the next two, switch the order of the next two, and so on. For example, if the array initially stores these values:

public static void swapPairs(String[] a){ for (int i = 0; i<a.length/2; i++){ String switchElements= a[2*i]; a[2 * i] = a[2 * i+1]; a[2*i+1] = switchElements; } System.out.print("{"); for(int x = 0; x<a.length-1; x++){ System.out.print(a[x] + ", "); } System.out.print(a[a.length-1]+"}"); }

Write a method called wordLengths that accepts a Scanner representing an input file as its argument. Your method should read from the given file, count the number of letters in each token in the file, and output a result diagram of how many words contain each number of letters. Use tabs before the asterisks so that they'll line up. If there are no words of a given length, omit that line from the output.

public static void wordLengths(Scanner scan) { int[] tally = new int[100]; while (scan.hasNext()){ String token = scan.next(); tally[token.length()]++; } for(int i = 0; i<tally.length; i++){ if (tally[i] != 0){ System.out.print(i+": " + tally[i]+"\t"); for(int x = 0; x<tally[i]; x++){ System.out.print("*"); } System.out.println(); } } }

How are constructors initialized?

public type(parameters) { statements; } - No return type is specified; it implicitly "returns" the new object being created.

Add mutator methods called setFirstName, setMiddleInitial, and setLastName to your encapsulated version of the Name class from the last exercise. Give the parameters the same names as your fields, and use the keyword this in your solution.

public void setFirstName(String firstName){ this.firstName = firstName; } public void setMiddleInitial(char middleInitial){ this.middleInitial = middleInitial; } public void setLastName(String lastName){ this.lastName = lastName; }

What is an example of a mutator method?

setLocation, translate

How is this used to refer to call one constructor to another?

this(parameters);

How is this used to refer to a field?

this.field

How is this used to refer to call a method?

this.method(parameters);

What are the states for the Point class?

x/y data called fields.

What elements does the array numbers contain after the following code is executed? (Write the elements in the format: {0, 1, 2, ...} ) int[] numbers = new int[8]; numbers[1] = 4; numbers[4] = 99; numbers[7] = 2; ​ int x = numbers[1]; numbers[x] = 44; numbers[numbers[7]] = 11;

{0,4,11,0,44,0,0,2}

Fill in the array with the values that would be stored after the code executes: int[] list = {2, 18, 6, -4, 5, 1}; for (int i = 0; i < list.length; i++) { list[i] = list[i] + (list[i] / list[0]); }

{3, 24, 8, -5, 6, 1}

Fill in the array with the values that would be stored after the code executes: int[] data = new int[8]; data[0] = 3; data[7] = -18; data[4] = 5; data[1] = data[0]; ​ int x = data[4]; data[4] = 6; data[x] = data[0] * data[1];

{3, 3, 0, 0, 6, 9, 0, -18}


Kaugnay na mga set ng pag-aaral

Strategies for Health Education Final

View Set

Chapter 25- Plant Responses + adaptations

View Set

Leadership CH 6 - delegation and prioritizing of client care staffing

View Set

Principios de anatomía y fisiología tortora, introducción al cuerpo humano cap. 1, (pag. 45) términos anatómicos

View Set

PERSONAL FINANCE CHAPTER 3 KEY TERMS

View Set

MCQ 3 - Elasticities of Demand and supply

View Set

Ratios & Proportions:Lets nail this now

View Set

Ch. 4 Prenatal Care and Adaptations to pregnancy

View Set

ch. 9 - the flow of food: service

View Set