class FinnTekstI2DArray { private static int riktig = 0; private static int feil = 0; public static void main(String[] args) { testFinnTekst(); testTomArray(); System.out.println("-----------------------------------------------"); System.out.println(riktig + " riktig -- " + feil + " feil"); } private static void sjekk(String expected, String calculated, String message) { if (calculated.equals(expected)) { System.out.println("Riktig! - " + calculated); riktig++; } else { System.out.println("Feil! paa " + message + " - Fikk: " + calculated + " Forventet verdi: " + expected); feil++; } } public static void testFinnTekst() { String[][] ord1 = {{"Dette", null, null}, {"er", "en", null}, {null, "sti", "!"}}; String[][] ord2 = {{"Her", "er", null, null}, {null, "en", "tekst", null}, {null, null, "tenk!", null}, {null, null, null, null}}; String expected1 = ""; for (String[] rad : ord1) { for (String ord : rad) { if (ord != null) { expected1 += ord; } } } sjekk(expected1, finnTekst(ord1), "Test av finnTekst ord1"); String expected2 = ""; for (String[] rad : ord2) { for (String ord : rad) { if (ord != null) { expected2 += ord; } } } sjekk(expected2, finnTekst(ord2), "finnTekst Ord2"); } public static void testTomArray () { sjekk("", finnTekst(null), "test av finnTekst null"); sjekk("", finnTekst(new String[10][10]), "test av finnTekst empty array"); } public static String finnTekst(String[][] ord){ if (ord == null || ord[0][0] == null) { return ""; } return finnTekst(ord, 0, 0); // begynner på første indeks / celle } public static String finnTekst(String[][] ord, int posx, int posy) { String current = ""; if (ord[posx][posy] != null){ current = ord[posx][posy]; if (posx == ord.length - 1) { //siste rad if (posy == (ord[ord.length - 1].length - 1)) { //siste kolonne og siste rad return current; } return current + finnTekst(ord, posx, posy + 1); //siste rad men ikke siste kolonne } else if (posy == (ord[ord.length - 1].length - 1)) { //siste kolonne men ikke siste rad return current + finnTekst(ord, posx + 1, posy); } return current + finnTekst(ord, posx + 1, posy) + finnTekst(ord, posx, posy + 1); //vanlig "celle" } return current; // null "celle" } }