2 answers

Program Overview This brief exercise is designed for you to consider how reference variables behave when...

Question:

Program Overview This brief exercise is designed for you to consider how reference variables behave when you are passing them1.2 Method name: readStudentNames Purpose: This method accepts an ArrayList of strings as a parameter. It loops through the AHow to Implement a for-each loop A for-each loop has the following structure. for (varType tmpVariable : dataStructure) e.g.Sample Output **** Passing Refereences - Reading 5 Names **** Main Method: Passing an Array, nameArray, by-value readStudentN

Program Overview This brief exercise is designed for you to consider how reference variables behave when you are passing them as arguments by-value. Instructions Name your class References.java. 1. Implement the following methods. 1.1 Method name: readStudentNames Purpose: This method accepts an array of strings as a parameter. It loops through the array and asks the user to input names. It populates the array of strings with the names. Parameters: an array of Strings, stringArray Return type: void In the body of the method: . • Put in a println telling the user that you are using the stringArray parameter Loop through the entire array o Prompt the user to enter a name and use your counter. o Read a name and assign it to the current element of the array. Use index i.
1.2 Method name: readStudentNames Purpose: This method accepts an ArrayList of strings as a parameter. It loops through the ArrayList and asks the user to input names. It then populates the ArrayList with the names. Parameters: an ArrayList of Strings, stringList Return type: void When using ArrayLists, remember to import the class and to use for specifying the data type. In the body of the method: • Put in a println telling the user that you are using the stringList parameter • Using a for structure, loop 5 times (hard code 5 here since we don't have an array length!) o Prompt the user to enter a name and use your counter. o Read a name and add it to your ArrayList parameter variable using its add method. You can do a nested method call here and do it all in one line! e.g. arrayListName.add(arguments); 2. In the main method, insert the following lines of code, • Put in a printIn statement showing that you are going to pass an array by value • Declare an array of strings as a local variable and call it nameArray. Initialize it and allocate a total of 5 elements. • Call the readstudentNames method and pass the name Array as an argument. • Loop through the entire nameArray o Print the value of the strings inside the array to the console. • Put in a printIn statement showing that you are going to pass an ArrayList by value • Declare and initialize and ArrayList of Strings as a local variable. Name it nameArrayList. • Call the readstudentNames method and pass name ArrayList as an argument. • Using a for-each loop, loop through the name ArrayList (see below for a refresher) o Print the value of the temporary string to the console.
How to Implement a for-each loop A for-each loop has the following structure. for (varType tmpVariable : dataStructure) e.g. for (int n : scores) read as: for each int n in scores If we wanted to print all integers in the scores data structure, we would type: println(n) This would work because n would have a different value each time. It is a temporary variable whose value changes each iteration. A popular convention is to use the first letter of the data type as the temporary variable name, e.g. int i, String s, double d, char c, etc. Learning Points Note that arrays and ArrayLists are references and behave differently when passed as arguments as opposed to the behavior seen when passing primitive types such as int and double. Note how you are able to access the entire array of variables that are not declared within a given method if they are passed to that method. Consider the implications: if you pass a reference and that reference leads to other variables - all those variables become fully accessible. Optional Learning Exercise Within the main method where you have your array, nameArray, declare another array called duplicateArray. Declare it but do not allocate elements to it. Assign nameArray to duplicateArray (duplicateArray goes on the left hand side of the assignment since we're assigning “to” it). Change the value of any one element of duplicateArray. Put a breakpoint on this line. After that line, change the value of any one element of nameArray. Run this program in debug mode. When you get to the break point, pull up the Variables window and look at the contents of nameArray and duplicateArray. Monitor their contents. You should see that when you change an element of nameArray it actually changes both the arrays. When you change an element of duplicateArray, it also actually changes both the arrays. Make sure you understand why this is happening: there is only one array!
Sample Output **** Passing Refereences - Reading 5 Names **** Main Method: Passing an Array, nameArray, by-value readStudentNames Method: Putting values inside stringArray parameter Enter name 1: Balin Enter name 2: Bilbo Enter name 3: Pippin Enter name 4: Merry Enter name 5: Samwise Main Method: The contents of nameArray are: Balin Bilbo Pippin Merry Samwise Main Method: Passing an ArrayList, nameArrayList, by-value readStudentNames Method: Putting values inside stringListparameter Enter name 2: Odo Enter name 3: Worf Enter name 4: Jadzia Enter name 5: Kira Enter name 6: Ezri Main Method: The contents of nameArrayList are: Odo Worf Jadzia Kira Ezri

Answers

// References.java

import java.util.Scanner;

public class References {

/**
   * method that accepts an array of strings as a parameter. It loops through the array
   * and asks the user to input names. It populates the array of strings with the names.
   * @param stringArray, an array of Strings
   */
   public static void readStudentNames(String[] stringArray)
   {
       Scanner keyboard = new Scanner(System.in);
       System.out.println("readStudentNames Method: Putting values inside stringArray parameter");
       // loop over the array, accepting strings for each array element
       for(int i=0;i<stringArray.length;i++)
       {
           System.out.print("Enter name "+(i+1)+": ");
           stringArray[i] = keyboard.nextLine();
       }
   }
  
   /**
   * method that accepts an ArrayList of strings as a parameter. It loops through the ArrayList
   * and asks the user to input names. It populates the ArrayList with the names.
   * @param stringArray, an ArrayList of Strings
   */
   public static void readStudentNames(ArrayList<String> stringList)
   {
       Scanner keyboard = new Scanner(System.in);
       System.out.println("readStudentNames Method: Putting values inside stringList parameter");
       // loop 5 times, to input 5 names into the array list
       for(int i=0;i<5;i++)
       {
           System.out.print("Enter name "+(i+1)+": ");
           stringList.add(keyboard.nextLine());
       }
   }
  
   public static void main(String[] args) {
  
       System.out.println("\t****** Passing References - Reading 5 Names *******");
       System.out.println("\nMain Method: Passing an Array, nameArray, by-value");
       String[] nameArray = new String[5];
       readStudentNames(nameArray);
       System.out.println("\nMain Method: The contents of nameArray are:");
       for(int i=0;i<nameArray.length;i++)
           System.out.println(nameArray[i]);
      
       System.out.println("\nMain Method: Passing an ArrayList, nameArrayList, by-value");
       ArrayList<String> nameArrayList = new ArrayList<String>();
       readStudentNames(nameArrayList);
       System.out.println("\nMain Method: The contents of nameArray are:");
       for(String name : nameArrayList)
           System.out.println(name);
   }  
}

// end of References.java

Output:

****** Passing References - Reading 5 Names ******* Main Method: Passing an Array, nameArray, by-value readStudentNames Metho



.

// References.java

import java.util.Scanner;

public class References {

/**
   * method that accepts an array of strings as a parameter. It loops through the array
   * and asks the user to input names. It populates the array of strings with the names.
   * @param stringArray, an array of Strings
   */
   public static void readStudentNames(String[] stringArray)
   {
       Scanner keyboard = new Scanner(System.in);
       System.out.println("readStudentNames Method: Putting values inside stringArray parameter");
       // loop over the array, accepting strings for each array element
       for(int i=0;i<stringArray.length;i++)
       {
           System.out.print("Enter name "+(i+1)+": ");
           stringArray[i] = keyboard.nextLine();
       }
   }
  
   /**
   * method that accepts an ArrayList of strings as a parameter. It loops through the ArrayList
   * and asks the user to input names. It populates the ArrayList with the names.
   * @param stringArray, an ArrayList of Strings
   */
   public static void readStudentNames(ArrayList<String> stringList)
   {
       Scanner keyboard = new Scanner(System.in);
       System.out.println("readStudentNames Method: Putting values inside stringList parameter");
       // loop 5 times, to input 5 names into the array list
       for(int i=0;i<5;i++)
       {
           System.out.print("Enter name "+(i+1)+": ");
           stringList.add(keyboard.nextLine());
       }
   }
  
   public static void main(String[] args) {
  
       System.out.println("\t****** Passing References - Reading 5 Names *******");
       System.out.println("\nMain Method: Passing an Array, nameArray, by-value");
       String[] nameArray = new String[5];
       readStudentNames(nameArray);
       System.out.println("\nMain Method: The contents of nameArray are:");
       for(int i=0;i<nameArray.length;i++)
           System.out.println(nameArray[i]);
      
       System.out.println("\nMain Method: Passing an ArrayList, nameArrayList, by-value");
       ArrayList<String> nameArrayList = new ArrayList<String>();
       readStudentNames(nameArrayList);
       System.out.println("\nMain Method: The contents of nameArray are:");
       for(String name : nameArrayList)
           System.out.println(name);
   }  
}

// end of References.java

Output:

****** Passing References - Reading 5 Names ******* Main Method: Passing an Array, nameArray, by-value readStudentNames Metho

.

Similar Solved Questions

1 answer
2. average variable cost offers a degree of _______ cost per item. a. marginal b. variable...
2. average variable cost offers a degree of _______ cost per item. a. marginal b. variable c. fixed d. total 3. short run is the period of time in which ________ elements of production exist. a. fixed b. average c. variable d. marginal 4. which of the following cost are variable costs for a cand...
2 answers
Hilltop Brokers Inc. is offering 1,300 shares of stock in a Dutch auction. The bids include:...
Hilltop Brokers Inc. is offering 1,300 shares of stock in a Dutch auction. The bids include: Bidder Quantity Price А 350 $22 B 200 $21 С 650 $20 D 1,000 $18 E 300 $16 How much cash will Hilltop receive from selling these shares? Ignore all transaction and flotation costs. $26,000 $22,800...
1 answer
Ocator assignment-Hake&inprogress talse During Year 1, its first year of operations, Gelies Company purchased two available-for-sale...
ocator assignment-Hake&inprogress talse During Year 1, its first year of operations, Gelies Company purchased two available-for-sale investments as Security Hawking Inc. 570 $19,266 1,540 27,104 Assume that as of December 31, Year 1, the Hawking Inc., stock hed a market value of $40 per share an...
1 answer
Window 92 % Tools Edit View Go Help Tue 9:07 am IMG 7349.PNG QUESTION 1 The...
Window 92 % Tools Edit View Go Help Tue 9:07 am IMG 7349.PNG QUESTION 1 The hydraulic cylinder C gives end A of the link AB, with the length of L = 2 m, velocity VA = 2 m/s to the left. Calculate for the instant when 0-30° the velocity of the centre of the slider B in the vertical guide and the ...
1 answer
2. (20 points) Write tuple calculus and domain calculus expressions for the following RA operations. A....
2. (20 points) Write tuple calculus and domain calculus expressions for the following RA operations. A. (10 points) SELECT P=r (R(P, Q, R)): B. (10 points) PROJECT <P, Q> (R(P, Q, R)):...
1 answer
Bananas are somewhat radioactive due to the presence ofsubstantial amounts ofpotassium. Potassium 40 decays by two...
Bananas are somewhat radioactive due to the presence ofsubstantial amounts ofpotassium. Potassium 40 decays by two different paths: (89.3%) (1Q796) K Ca+b Ar + b' 19 channels...
1 answer
A nurse assesses a client who is experiencing an acid-base imbalance. The client's arterial blood gas...
A nurse assesses a client who is experiencing an acid-base imbalance. The client's arterial blood gas values are pH 7.33, PaO2 88 mm Hg. PaCO2 38 mm Hg, and HCO3- 19 mEq/L. Which assessment should the nurse perform first? A. Cardiac rate and rhythm B. Skin and mucous membranes C. Musculoskeletal...
1 answer
In one dimension Mech COnscretion of moment HW-62 3. Two astronauts A and B. narticipate in...
in one dimension Mech COnscretion of moment HW-62 3. Two astronauts A and B. narticipate in three collision experiments in a weightless, friction environment. In each experiment, astronaut B is initially at rest, and astronaut A has an initial momentum of 20 kg-m/s to the right. (The velocities of t...
1 answer
How do you evaluate #|- 6| + | - 7| - 10#?
How do you evaluate #|- 6| + | - 7| - 10#?...
1 answer
Re doing. A Pythagorean triple is a set of integers (a, b, c) satisfying a2+bc2. Write pseudocode...
re doing. A Pythagorean triple is a set of integers (a, b, c) satisfying a2+bc2. Write pseudocode (or Matlab code) that will output the number of unique Pythagorean triples that satisfy c< 200. [Unique means that you should not count (a 3, b 4, c 5) and (a 4, b 3, c 5) as two different triples, f...
1 answer
Balance sheet Labels and Amounts Descriptions Balance Sheet Instructions Dynamic Weight Loss Co. offers personal weight...
Balance sheet Labels and Amounts Descriptions Balance Sheet Instructions Dynamic Weight Loss Co. offers personal weight reduction consulting services to individuals. After all the accounts have been closed on June 30, 2017, the end of the fiscal year, the balances of selected accounts from the ledge...
1 answer
5. Which cell types produce mucus? Choose all that apply. (0.5 pt) a. neck cells in...
5. Which cell types produce mucus? Choose all that apply. (0.5 pt) a. neck cells in the stomach b. neck cells in the large intestine c. chief cells in the stomach d. chief cells in the small intestine e. goblet cells in the stomach f. goblet cells in the small intestine g. goblet cells in the large ...
1 answer
Need help completing journal entries Exercise 4-15A Recording purchases, returns, and allowances-periodic LO P5 Apr. 2...
need help completing journal entries Exercise 4-15A Recording purchases, returns, and allowances-periodic LO P5 Apr. 2 Purchased $6,300 of merchandise from Lyon Company with credit terms of 2/15, 1/60, invoice dated April 2, and FOB shipping point. 3 Paid $353 cash for shipping charges on the A...
1 answer
Please solve using Kirchhoffs rules to determine the voltage and current through each resistor. 4ΚΩ V2...
Please solve using Kirchhoffs rules to determine the voltage and current through each resistor. 4ΚΩ V2 6ον 80ν ΟΙ R2 >3kΩ ΜΜΜ 2kΩ....
1 answer
5. (This problem, due to Steven Strogatz, appeared in the New York Times.) Before going on...
5. (This problem, due to Steven Strogatz, appeared in the New York Times.) Before going on vacation for a week, you ask your spacey friend to water your ailing plant. Without water, the plant has a 90% chance of dying. Even with proper watering, it has a 20% chance of dying. The probability that you...
1 answer
The initial data set is given in the table below: R2 = 30 1, R2 =...
The initial data set is given in the table below: R2 = 30 1, R2 = 40 1, R2 = 60 2, E; =3 V, E2 = 6 V 1, (in A) 0.061 1. (in A) 0.053 V (in V) 0.343 V in v 2.58 V: (in V) 3.2 L (in A) Experimental 0.105 Theoretical % Error Your job is to calculate all the theoretical values of currents and voltage dr...
1 answer
Discussion Questions from "Death beyond Constant Love" What news did Senator Onésimo Sánchez receive near the...
Discussion Questions from "Death beyond Constant Love" What news did Senator Onésimo Sánchez receive near the beginning of the story? How did this existential revelation affect his attitudes and decisions throughout the story? Be specific How does Gabriel Garcia Marquez incorpo...