CompSci 100EJB2.1Java Basics – Arraysÿ Should be a very familiar idea Problem: Deal with exam grades in a courseo Could have variable for each studento Would need unique name for each variableo Need lots of custom codeo Instead, assume named array; use index to get valuesÿ Example: method to count number of A gradespublic static int getAs(int[] grades) {int aCount = 0;for (int k=0;k<grades.length;k++){if (grades[k] >= 90) {aCount++;}return aCount;}ÿExplainCompSci 100EJB2.2Java Basics – Arraysÿ Array Bounds Index must in range0 <= k < grades.length Else get ArrayIndexOutOfBoundsExceptionÿ Short Circuit Evaluation Allows expression of the formif (k>=0 && k<grades.length && grades[k] >= 90) {aCount++;} Safe from exception Order important! Holds for any chain of ANDed terms Similar rules for chain of ORed termsCompSci 100EJB2.3Java Basics – Arraysÿ Creating Arrays (by example)int[] counts = new int[101];String[] colors = new String[3];Counter[] tallies = new Counter[10];int[] codes;codes = new int[17];ÿ Using Initializer ListsString[] colors = {”red”, ”green”, ”blue”};double[] shims = {1.0, 1.1, 1.3, 1.6, 1.9, 2.5};ÿ Initializing Object Arrays For most object arrays, need to create objects in the arrayfor (int k = 0; k < tallies.length; k++){tallies[k] = new Counter();}CompSci 100EJB2.4Java Basics – Arraysÿ Arrays are Objects Behavior of arrays similar to other objects Thus grades.length worksÿ Assignments (Warning!) Since array identifiers are just referenceso Array assignment doesn’t create new array! Use newArrayname=arrayname.clone();o This works well for arrays of primitives What happens for arrays of objects?ÿ Shallow vs Deep Copy Java vs C++CompSci 100EJB2.5Java Basics – Simple I/Oÿ Output methods (Java console) System.out.println(. . .); System.out.print(. . .); Overloaded for String and primitive typesÿ Warning: tries to convert argument to string What is the output for the following?int k=5;System.out.println(k);System.out.println(k + 1);System.out.println(k - 1);System.out.println(”the answer is ” + k);System.out.println(”the answer is ” +k+1);System.out.println(”the answer is ” +k-1);CompSci 100EJB2.6Java Basics – Simple I/Oÿ Input methods (Java console) Need to use Scanner object Parses the input and give us back tokens.ÿ Scanner Class Use nextType() method where type is primitive Use next() for StringScanner s = new Scanner(System.in);double d = s.nextDouble();Strings w = s.next(); You’ve used this in labÿ Check out Scanner classCompSci 100EJB2.7Java Basics – Classes and Packagesÿ Class must be in file Filename must be className.java I it is an application, it must includepublic static void main(String[] args) methodÿ Nested Classes Defined inside of a class Usually used only by the outer classÿ Packages A set of classes in a subdirectory can be a package Directory name matches package name Each file must start withpackage
View Full Document