public class ArrayBasics
2: import java.util.Scanner;
4: /**
5: * A class to create and use some arrays.
6: * It doesn't do much of anything.
7: *
8: * @author Mark Young (A00000000)
9: */
10: public class ArrayBasics {
12: public static void main(String[] args) {
13: // introduce self
14: System.out.println("\n"
15: + "Just doing some array things."
16: + "Look at the code and compare it to the output.\n");
18: // an array type is just another data type
19: int anIntVar; // type int
20: int[] aBunchOfIntVars; // type int[]
22: // you can make an array out of /any/ data type
23: double[] aBunchOfDoubleVars; // doubles
24: String[] aBunchOfStringVars; // Strings
25: Scanner[] aBunchOfScannerVars; // Scanners
26: int[][] aBunchOfIntArrayVars; // int[]s (!)
28: // like other variables, array vars need to be given values
29: // like Scanners, use the word "new" to make the value
30: Scanner kbd = new Scanner(System.in);
31: // unlike Scanners, it's []s after the data type, not ()s
32: double[] someNumbers = new double[20];
33: String[] someWords = new String[1000];
35: // size of the array can be a variable
36: System.out.print("How many lines will you be entering? ");
37: int numLines = kbd.nextInt();
38: kbd.nextLine();
39: String[] theLines = new String[numLines];
41: // Array usually used as a group
42: // (doing the same thing to each element)
43: for (int i = 0; i < someNumbers.length; i++) {
44: // pick out array elements using []
45: someNumbers[i] = Math.sqrt(i);
46: // number inside the brackets is called an index
47: }
48: // but you can use array elements as individual variables
49: System.out.println("someNumbers[10] == " + someNumbers[10]);
51: // read some lines
52: System.out.println("\n"
53: + "Let's enter those lines, now:");
54: for (int i = 0; i < numLines; i++) {
55: theLines[i] = kbd.nextLine(); // no need to tidy up
56: }
58: // print the lines (reversed)
59: System.out.println("\n"
60: + "Here are the lines you entered, in reverse order:");
61: for (int i = numLines - 1; i >= 0; i--) {
62: System.out.println("\t\"" + theLines[i] + "\"");
63: }
64: System.out.print("\n---Press Enter to continue---");
65: kbd.nextLine();
67: // print the square roots
68: System.out.println("\n"
69: + "And here are the square roots I calculated earlier:");
70: for (int i = 0; i < someNumbers.length; i++) {
71: System.out.println("\tsqrt(" + i + ") is " + someNumbers[i]);
72: }
73: System.out.println();
74: }
76: }