Question

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

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
0 0
Add a comment Improve this question
Answer #1

Sign Up to Unlock the answer FREE

Already have an account? Log in

// 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



answered by: ANURANJAN SARSAM
Add a comment
Answer #2

Sign Up to Unlock the answer FREE

Already have an account? Log in

// 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

Add a comment
Know the answer?
Add Answer to:
Program Overview This brief exercise is designed for you to consider how reference variables behave when...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write you code in a class named HighScores, in file named HighScores.java. Write a program that...

    Write you code in a class named HighScores, in file named HighScores.java. Write a program that records high-score data for a fictitious game. The program will ask the user to enter five names, and five scores. It will store the data in memory, and print it back out sorted by score. The output from your program should look approximately like this: Enter the name for score #1: Suzy Enter the score for score #1: 600 Enter the name for score...

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

  • Lab Topics • The basics of Array object Use the following Coding Guidelines • When declaring...

    Lab Topics • The basics of Array object Use the following Coding Guidelines • When declaring a variable, you usually want to initialize it. Remember you cannot initialize a number with a string. Remember variable names are case sensitive. Use tabs or spaces to indent code within blocks (code surrounded by braces). Use white space to make your program more readable. Use comments after the ending brace of classes, methods, and blocks to identify to which block it belongs. Problem...

  • I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according...

    I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the...

  • Write a new program called TrickOr Treat that will do the following 1. In a while...

    Write a new program called TrickOr Treat that will do the following 1. In a while loop, say "Trick or Treat!" and allow the user to type in the name of a candy and store it in an ArrayList. Once the user types "Trick", then the loop should stop. Then, print out the total number of candies on the screen. (See example below) [1 points] 2. Write a method called countSnickers that will take an ArrayList of candy as an...

  • Array lists are objects that, like arrays, provide you the ability to store items sequentially and...

    Array lists are objects that, like arrays, provide you the ability to store items sequentially and recall items by index. Working with array lists involves invoking ArrayList methods, so we will need to develop some basic skills. Let's start with the code below: The main method imports java.utii.ArrayList and creates an ArrayList that can hold strings by using the new command along with the ArrayList default constructor. It also prints out the ArrayList and, when it does, we see that...

  • Please create a program answering the following question in C PROGRAMMING. CorrectFormation Create a program and...

    Please create a program answering the following question in C PROGRAMMING. CorrectFormation Create a program and locally declare in main fname and Iname and completeName. Ask the user for their first and last name. Put the values into fname and Iname. You will create a function that is called as followed oinNames( fname, Iname, completeName ); You will pass the first name array, the last name array, and the array that will contain the complete name. The function named joinNames...

  • ArraysAndFiles.java and PartiallyFilledArray.java. They are shells that do not do anything. You will be adding code...

    ArraysAndFiles.java and PartiallyFilledArray.java. They are shells that do not do anything. You will be adding code after the comments in the main method and using the javadoc documentation to implement the other methods. Task 1: Send array data to the screen In ArraysAndFiles.java, create a new method printOnScreen and compile it. In the main method of ArraysAndFiles.java, add the code to declare and initialize the array of Strings and call printOnScreen to print the array on the screen. Task 2:...

  • C# program to calculate tournament stat averages

    Write a program in C# using Visual Studio to determine statistics for a video game tournament. The user will input names and scores of all tournamentplayers. The program will calculate the average score and display the players who scored below average.??The program will implement these functions:• Main(): Declares variables for the number of players and average score, and two arrays of size 100: one to store player names and the other to store their respectivescores. Calls the following functions in...

  • Tasks Write a program that prints in text mode Project 2 written by YOURNAME And shows...

    Tasks Write a program that prints in text mode Project 2 written by YOURNAME And shows in a graphical way, as shown below, the names stored in a file. The coordinates to print the names will be also read from another file. Here is an example of what your graphic output should look like with the two files that are provided for test purposes. Drawing Panel Adam Bernie Cameron Daniel Fanny Gerard Harold Issac Jackie Raitlyn Note that the colors...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
Active Questions
ADVERTISEMENT