Back to the Program-A-Day homepage
Problem
Today we'll look at returning a new array from a different method.
Let's now expand on the printArray program created in the previous problem. Recall you created a method to print the names of students stored in different arrays for different classes. You now have been given an additional class to teach, COMP2040, and must input a new list of students for this class. To do this, you will need to create an additional method in the existing program.
Take the sample solution from printArray below and add a fillArray method to it. This method should accept a number as an integer as input, representing the number of students in the class, and return an array of Strings, containing the students names, as output. You will need some method of taking user input within this method.
public class PrintArray{
public static void main (String [] args){
String [] comp1010 = { "Adam", "Bob", "Carl", "David", "Edward"};
String [] comp1020 = { "Amy", "Beth", "Cindy", "Dawn", "Ellen"};
String [] comp1260 = { "Mike", "Mary", "Matthew", "Megan", "Moe"};
System.out.println("COMP 1010:");
printArray(comp1010);
System.out.println("COMP 1020:");
printArray(comp1020);
System.out.println("COMP 1260:");
printArray(comp1260);
System.out.println("--End of Processing--");
}
public static void printArray(String [] courseList){
for (int i=0; i<courseList.length;i++){
System.out.println(courseList[i]);
}
System.out.println();
}
}
Use the printArray method to print out the all class lists after creating the new list.
|
|
Arrays and Methods
|
Solution
To create the fillArray method, use a loop that for each index of the array prompts the user to enter a name, takes the users input, and then inserts it into the array.
|
Code
Solution Code
import java.io.*;
class Students{
public static void main (String [] args){
String [] comp1010 = fillArray(10);
printArray(comp1010);
System.out.println("--End of Processing--");
}
public static void printArray(String [] courseList){ //note that the method is void, and the input variable is an array of Strings
//We called the array "courseList", since this can refer to any of the arrays
//we send it
for (int i=0; i<courseList.length;i++){ //for loop to go through each element in the array
System.out.println(courseList[i]); //print the current element
}
System.out.println(); //add a blank line after the list of students
}
public static String[] fillArray(int size){
String[] names = new String[size]; //an Array to hold the entered names
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //a BufferedReader to accept user input of names
for (int i=0;i<names.length;i++){
System.out.print("Please enter a name: "); //prompt the user for a name
try{
names[i] = br.readLine(); //insert the user input name into the array
}
catch (IOException ioe){
System.out.println("ERROR!!!");
System.exit(1);
}
}
return names;
}
}
|
Back to the Program-A-Day homepage