001 /**
002 * Esimerkki dynaamisesta taulukosta
003 * @author Vesa Lappalainen
004 * @version 1.0, 02.03.2002
005 */
006
007 public class Taulukko {
008 public class TaulukkoTaysiException extends Exception {
009 TaulukkoTaysiException(String viesti) { super(viesti); }
010 }
011
012 private int alkiot[];
013 private int lkm;
014
015 public Taulukko() {
016 alkiot = new int[10];
017 }
018
019 public Taulukko(int koko) {
020 alkiot = new int[koko];
021 }
022
023 public void lisaa(int i) throws TaulukkoTaysiException {
024 if ( lkm >= alkiot.length ) throw new TaulukkoTaysiException("Tila loppu");
025 alkiot[lkm++] = i;
026 }
027
028 public String toString() {
029 StringBuffer s = new StringBuffer("");
030 for (int i=0; i<lkm; i++)
031 s.append(" " + alkiot[i]);
032 return s.toString();
033 }
034
035 public void set(int i, int luku) throws IndexOutOfBoundsException {
036 if ( ( i < 0 ) || ( lkm <= i ) ) throw new IndexOutOfBoundsException("i = " + i);
037 alkiot[i] = luku;
038 }
039
040 public int get(int i) throws IndexOutOfBoundsException {
041 if ( ( i < 0 ) || ( lkm <= i ) ) throw new IndexOutOfBoundsException("i = " + i);
042 return alkiot[i];
043 }
044
045 public static void main(String[] args) {
046 Taulukko luvut = new Taulukko();
047 try {
048 luvut.lisaa(0); luvut.lisaa(2);
049 luvut.lisaa(99);
050 } catch ( TaulukkoTaysiException e ) {
051 System.out.println("Virhe: " + e.getMessage());
052 }
053 System.out.println(luvut);
054 luvut.set(1,4);
055 System.out.println(luvut);
056 int luku = luvut.get(2);
057 System.out.println("Paikassa 2 on " + luku);
058 try {
059 luvut.set(21, 4);
060 }
061 catch (IndexOutOfBoundsException e) {
062 System.out.println("Virhe: " + e.getMessage());
063 }
064 }
065 }