VL-Programmieren/VL12/Aufgabe02/Aufgabe02.java

63 lines
1.9 KiB
Java
Raw Normal View History

2024-05-01 21:19:04 +00:00
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(".", "/");
}
}