From cea993fcd1478884a3582bbcdc57bf59d60324d4 Mon Sep 17 00:00:00 2001 From: Sebastian Brosch Date: Wed, 1 May 2024 23:19:04 +0200 Subject: [PATCH] Vorlesung 12 / Aufgabe 2 --- VL12/Aufgabe02/Aufgabe02.java | 62 ++++++++++++++++++++++++++++++++++ VL12/Aufgabe02/input/input.txt | 2 ++ 2 files changed, 64 insertions(+) create mode 100644 VL12/Aufgabe02/Aufgabe02.java create mode 100644 VL12/Aufgabe02/input/input.txt diff --git a/VL12/Aufgabe02/Aufgabe02.java b/VL12/Aufgabe02/Aufgabe02.java new file mode 100644 index 0000000..c0b6715 --- /dev/null +++ b/VL12/Aufgabe02/Aufgabe02.java @@ -0,0 +1,62 @@ +package VL12.Aufgabe02; + +import java.io.IOException; +import java.io.StreamTokenizer; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Paths; + +/** + * Vorlesung 12 - Ein- und Ausgabe - Aufgabe 2 + * @author Sebastian Brosch + */ +public class Aufgabe02 { + public static void main(String[] args) { + try { + int words = 0; + int numbers = 0; + + StringReader stringReader = new StringReader(getInputString(getPathFromPackage() + "/input/input.txt")); + StreamTokenizer streamTokenizer = new StreamTokenizer(stringReader); + + while(streamTokenizer.nextToken() != StreamTokenizer.TT_EOF) { + switch(streamTokenizer.ttype) { + case StreamTokenizer.TT_WORD: + words++; + System.out.printf("ZEICHENKETTE:\t%s\n", streamTokenizer.sval); + break; + case StreamTokenizer.TT_NUMBER: + numbers++; + System.out.printf("ZAHL:\t\t%.0f\n", streamTokenizer.nval); + break; + } + } + + System.out.printf("Gelesene Zahlen: %d\n", numbers); + System.out.printf("Gelesene Zeichenketten: %d\n", words); + System.out.printf("Insgesamt gelesene Token: %d\n", (numbers + words)); + } catch (Throwable e) {;} + } + + /** + * Method to get the content of a file as a string. + * @param inputPath The path of the file. + * @return The content of the file or an empty string if the file is not available. + */ + private static String getInputString(String inputPath) { + try { + return new String(Files.readString(Paths.get(inputPath))); + } catch (IOException e) { + e.printStackTrace(); + return ""; + } + } + + /** + * Method to get the relative path based on the package name. + * @return The relative path of the package based on the package name. + */ + private static String getPathFromPackage() { + return Aufgabe02.class.getPackageName().replace(".", "/"); + } +} diff --git a/VL12/Aufgabe02/input/input.txt b/VL12/Aufgabe02/input/input.txt new file mode 100644 index 0000000..25e7b96 --- /dev/null +++ b/VL12/Aufgabe02/input/input.txt @@ -0,0 +1,2 @@ +Dieser Text hat 6 +Worte und 2 Zahlen. \ No newline at end of file