VL-Programmieren/VL12/Aufgabe02/Aufgabe02.java

69 lines
2.0 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
2024-05-06 20:19:27 +00:00
*
2024-05-01 21:19:04 +00:00
* @author Sebastian Brosch
*/
public class Aufgabe02 {
public static void main(String[] args) {
try {
2024-05-06 20:19:27 +00:00
int numberOfWords = 0;
int numberOfNumbers = 0;
2024-05-01 21:19:04 +00:00
StringReader stringReader = new StringReader(getInputString(getPathFromPackage() + "/input/input.txt"));
StreamTokenizer streamTokenizer = new StreamTokenizer(stringReader);
2024-05-06 20:19:27 +00:00
while (streamTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
switch (streamTokenizer.ttype) {
2024-05-01 21:19:04 +00:00
case StreamTokenizer.TT_WORD:
2024-05-06 20:19:27 +00:00
numberOfWords++;
2024-05-01 21:19:04 +00:00
System.out.printf("ZEICHENKETTE:\t%s\n", streamTokenizer.sval);
break;
case StreamTokenizer.TT_NUMBER:
2024-05-06 20:19:27 +00:00
numberOfNumbers++;
2024-05-01 21:19:04 +00:00
System.out.printf("ZAHL:\t\t%.0f\n", streamTokenizer.nval);
break;
}
}
2024-05-06 20:19:27 +00:00
System.out.printf("Gelesene Zahlen: %d\n", numberOfNumbers);
System.out.printf("Gelesene Zeichenketten: %d\n", numberOfWords);
System.out.printf("Insgesamt gelesene Token: %d\n", (numberOfNumbers + numberOfWords));
} catch (Throwable e) {
;
}
2024-05-01 21:19:04 +00:00
}
/**
* Method to get the content of a file as a string.
2024-05-06 20:19:27 +00:00
*
2024-05-01 21:19:04 +00:00
* @param inputPath The path of the file.
2024-05-06 20:19:27 +00:00
* @return The content of the file or an empty string if the file is not
* available.
2024-05-01 21:19:04 +00:00
*/
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.
2024-05-06 20:19:27 +00:00
*
2024-05-01 21:19:04 +00:00
* @return The relative path of the package based on the package name.
*/
private static String getPathFromPackage() {
return Aufgabe02.class.getPackageName().replace(".", "/");
}
}