Home Arrays
Arrays should be homogeneous
You should use arrays to store a related sequence of data which has all the same type. Do not try and use arrays has a hack to store multiple pieces of unrelated data. You should use loops to process arrays whenever possible.
When you first learn about arrays, it's very tempting to try and use them in such a way to return multiple unrelated pieces of information from a method at once:
public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] name = getData(input); String firstName = name[0]; String lastName = name[1]; //... } public static String[] getData(Scanner input) { System.out.print("First name: "); String firstName = input.next(); System.out.print("Last name: "); String lastName = input.next(); String[] result = {firstName, lastName}; return result; }
However, this is an abuse of arrays, and is a bit of a hack. It's better to use the proper mechanism for returning multiple values, which, in Java, is typically an object.
Unfortunately, in CSE 142 and 143, we don't really permit you to construct and return arbitrary objects from your methods. As a result, you're effectively restricted to returning one and only one conceptual "thing" from any given method at a time.
This may sometimes require you to rewrite or readjust your program. For example, we'd most likely have to rewrite the above program to look something like this:
public static void main(String[] args) { Scanner input = new Scanner(System.in); String firstName = prompt(input, "First name: "); String lastName = prompt(input, "Last name: "); //... } public static String prompt(Scanner input, String message) { System.out.print(message); return input.next(); }
Instead, you should use arrays for their intended purpose – to store a sequence of related data. If you use arrays properly, you'll as a consequence will almost always operate over them using a loop of some sort.