110 likes | 226 Views
CS12230 Introduction to Programming Lecture 9-2 – Arrays. There are LOTS of ways to have ‘many’ in Java:. ArrayList – done (part of a Java library) see CS211 where you will do many more! Arrays – here they are. Arrays. Occur in almost all languages In compiled languages FIXED length
E N D
There are LOTS of ways to have ‘many’ in Java: • ArrayList – done (part of a Java library) • see CS211 where you will do many more! • Arrays – here they are
Arrays • Occur in almost all languages • In compiled languages FIXED length • Faster execution than ArrayList • But more dangers of ‘falling off the end’ – Array Index out of bounds • Basic idea is you have something like: Card [] cards=new Card[52]; cards[i]=new Card(n,s); Called the index
Looks like the pictures we’ve drawn of ArrayList, but you do more work int num=0; Person[] people=new Person[6]; Person p=new Person(“fred”,”123456”); people[num]=p; num++: num mary 123456 sue 123456 3 fred 123456 for (int i=0; i<num; i++) { System.out.println( people[i].toString()); }
2 dimensional arrays – eg X and O /** * handles the Board in a text based X and O game */ public class Board{ private char[][] board; public Board() { board=new char[3][3]; blank(); } public String toString() { String ret="board is \n"; ret+="\n---1---2---3--\n"; for (int i=0;i<3;i++ ){ ret+=(i+1)+"| "; for (int j=0;j<3;j++) ret+= board[i][j]+" | "; ret+="\n-------------\n"; } return ret; } public void blank() { for (inti=0;i<3;i++ ) for (int j=0;j<3;j++) board[i][j]=' '; } public char valueAt(int row, int column) { return board[row-1][column-1]; } //etc etc
FINALLY, we can explain: public static void main(String args[]) { } This means a method called main which: • Is a class method (static) • Doesn’t return anything (void) • Accepts an array of Strings as parameters (String args[]) • Those parameters are the words on the line if you run from command line. So for instance: • If I type java GoodArt infile.txt • then args[] is length 1, args[0] is “infile.txt”
See also: • 9-week9-in-lab code: ConactList redone with arrays • And 14-lecture notes