Aufgabe2_Kellerautomat fertig gestellt mit Exception

This commit is contained in:
schrom01 2022-04-10 17:46:10 +02:00
parent 4feff96d73
commit 2eed96c8f4
2 changed files with 12 additions and 13 deletions

View File

@ -8,7 +8,9 @@ class Aufgabe2_KellerautomatTest {
void calculate() {
assertEquals(6664, Aufgabe2_Kellerautomat.calculate("34+62+89+43+***"));
assertEquals(58, Aufgabe2_Kellerautomat.calculate("31+78+987+1214++7++++++"));
assertEquals(-1, Aufgabe2_Kellerautomat.calculate("34+*"));
assertEquals(-1, Aufgabe2_Kellerautomat.calculate("8+9+7*2*"));
assertThrows(IllegalArgumentException.class,()->Aufgabe2_Kellerautomat.calculate("34+34+"));
assertThrows(IllegalArgumentException.class,()->Aufgabe2_Kellerautomat.calculate("34+*"));
assertThrows(IllegalArgumentException.class,()->Aufgabe2_Kellerautomat.calculate("8+9+7*2*"));
}
}

View File

@ -4,15 +4,19 @@ import java.util.Collections;
import java.util.List;
public class Aufgabe2_Kellerautomat {
private static String[] words = {"ZZO", "ZZOZZOO", "ZZZOO", "ZZOO", "ZZOZZO", "ZOZ"};
private static String[] words = {"34+62+89+43+***", "31+78+987+1214++7++++++", "34+34+", "34+*", "8+9+7*2*"};
public static void main(String[] args) {
for (String word : words) {
try {
calculate(word);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
public static int calculate(String word) {
public static int calculate(String word) throws IllegalArgumentException {
List<Character> wordChars = new ArrayList<>();
for (char symbol : word.toCharArray()) {
wordChars.add(symbol);
@ -38,7 +42,6 @@ public class Aufgabe2_Kellerautomat {
state = 1;
} else {
dontAccept(word);
return -1;
}
break;
case 1:
@ -49,7 +52,6 @@ public class Aufgabe2_Kellerautomat {
state = 2;
} else {
dontAccept(word);
return -1;
}
break;
case 2:
@ -68,7 +70,6 @@ public class Aufgabe2_Kellerautomat {
state = 2;
} else {
dontAccept(word);
return -1;
}
break;
case 3:
@ -78,7 +79,6 @@ public class Aufgabe2_Kellerautomat {
state = 4;
} else {
dontAccept(word);
return -1;
}
break;
case 4:
@ -94,7 +94,6 @@ public class Aufgabe2_Kellerautomat {
state = 3;
} else {
dontAccept(word);
return -1;
}
} else {
if (stackSymbol > -1) {
@ -102,7 +101,6 @@ public class Aufgabe2_Kellerautomat {
state = 5;
} else {
dontAccept(word);
return -1;
}
}
break;
@ -112,7 +110,6 @@ public class Aufgabe2_Kellerautomat {
state = 6;
} else {
dontAccept(word);
return -1;
}
break;
case 6:
@ -126,7 +123,7 @@ public class Aufgabe2_Kellerautomat {
}
private static void dontAccept(String word) {
System.out.println("Word: " + word + "\nnot accepted");
throw new IllegalArgumentException("Word: " + word + "\nnot accepted");
}
private static void accept(String word, int result) {