CodeGym
CodeGym University
Lernen
Kurs
Aufgaben
Umfragen & Quizze
Spiele
Hilfe
Zeitplan für einen Tritt in den Hintern
Community
Benutzer
Forum
Chat
Artikel
Erfolgsstorys
Aktivität
Rezensionen
Abonnements
Helles Design
Jetzt lernen
  • Alle Fragen
fullTimeAdventurer
Level 27
Chemnitz
  • 26.01.2022
  • 166Aufrufe
  • 5Kommentare

one cool hint please :)

Frage zur Aufgabe Long words
Java Core,  Level 9,  Lektion 11
Gelöst

Der erste Parameter der main-Methode ist file1 und der zweite ist file2.
file1 enthält durch Leerzeichen getrennte Wörter.
Schreibe in file2 eine durch Kommas getrennte Liste von Wörtern mit mehr als 6 Zeichen.
file2 darf nicht mit einem Komma enden.
Schließe die Streams.

Beispiel für die Ausgabe in file2:
lengthy,shortened,abbreviation

Anforderungen:
  • Das Programm darf KEINE Daten von der Konsole lesen.
  • Das Programm muss den Inhalt der ersten Datei lesen (verwende den FileReader-Konstruktor mit einem String-Parameter).
  • Der Dateieingabedatenstrom (FileReader) muss geschlossen werden.
  • Das Programm muss alle Wörter aus der ersten Datei in die zweite Datei schreiben, die länger als 6 Zeichen sind, getrennt durch Kommas (verwende FileWriter).
  • Der Dateiausgabedatenstrom (FileWriter) muss geschlossen werden.
package de.codegym.task.task19.task1925; /* Long words Die Lösung erklärt etwas mit args, das kenne ich noch nicht! muss ich erst noch lernen :) */ import java.io.*; import java.nio.CharBuffer; public class Solution { public static void main(String[] args) throws IOException { String fileName1 = args[0]; String fileName2 = args[1]; // Testfall // String fileName1 = "data.txt"; // String fileName2 = "result.txt"; FileReader fileReader = new FileReader(fileName1); FileWriter fileWriter = new FileWriter(fileName2); StringBuffer stringBuffer = new StringBuffer(); int temp = 0; while (true) { temp = fileReader.read(); // System.out.println(temp); // Wenn kein Ende und kein Leerzeichen if (temp > -1 && temp != 32) { stringBuffer.append((char) temp); // System.out.println(stringBuffer); } // Wenn Leerzeichen gesetzt if (temp == 32) { if (stringBuffer.length() > 6) { // System.out.println("Ich schreibe"); fileWriter.append(stringBuffer); fileWriter.append(','); } stringBuffer.delete(0, stringBuffer.capacity()); } // Wenn Ende if (temp == -1) { if (stringBuffer.length() > 6) { // System.out.println("Ich schreibe"); fileWriter.append(stringBuffer); } stringBuffer.delete(0, stringBuffer.capacity()); break; } temp = 0; } fileReader.close(); fileWriter.close(); } }
0
Kommentare (5)
  • Beliebt
  • Neu
  • Alt
Du musst angemeldet sein, um einen Kommentar schreiben zu können
Lisa
Level 41
26 Januar 2022, 22:00nützlich
easy, I'll give you three 😁 1. you ignore line breaks. Depending on the OS that's two different chars. ASCII values 10 and 13 (LF and CR). You need add these two values to your if clauses in lines 34 and 40 2. use length() instead of capacity(). The latter is not returning what you may expect 3. if the last write doesn't happen inside the last if block, you have a trailing , Maybe better would be to add all words > 6 chars to a list or a StringBuilder and then write to a file. You could save you a lot of headache if you wrap the FileReader inside a BufferedReader, then you could read entire lines. The readLine method removes the linebreak, too. Then split and check word length... piece of cake. When you use a list to add the words, Check if it's size is > 0, print the first word. Loop from indey 1 to list.size() and print ", nextWord"... cake eating continues 😜🤪 If you want to use a StringBuilder to create the output, just add "longWord, " and before you write remove the last 2 chars If you directly want to write to the file, then you'll need a boolean that holds if you have already written a word to disk. If not, just write the word. If there has been a word before, all following words should have a leading comma Oh and usually you use StringBuffer when using threads. If not, StringBuilder is probably the better choice (as it doesn't have the synchronization overhead of StringBuffer)
+1
fullTimeAdventurer Team Lead
27 Januar 2022, 15:01
Hi Lisa, thanks for your support. Your Idea with the BufferReader was great, so i get the prolem with the \n. I try it out but the auto Test still will not accept it. I test: for input in data.txt /* HalloHallo das ist Leerzeichen TextText Text */ and i get these result in result.txt /* HalloHallo,Leerzeichen,TextText */ - no space char - no , at the end witch test scenario i did not expect?
0
fullTimeAdventurer Team Lead
27 Januar 2022, 15:02
package de.codegym.task.task19.task1925;

/*
Long words

Die Lösung erklärt etwas mit args, das kenne ich noch nicht! muss ich erst noch lernen :)

*/

import java.io.*;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public static void main(String[] args) throws IOException {

//         // Argumente übergeben
//        String fileName1 = args[0];
//        String fileName2 = args[1];

        // Testfall
        String fileName1 = "data.txt";
        String fileName2 = "result.txt";

        // Datei einlesen ohne Leer vorn und hinten und separiert.
        BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName1));
        FileWriter fileWriter = new FileWriter(fileName2);

        ArrayList<String> stringArrayList = new ArrayList<>();

        while (bufferedReader.ready()) {
            String[] temp = bufferedReader.readLine().trim().split(" ");
            stringArrayList.addAll(Arrays.asList(temp));
        }
        // Zwischentest
//        for (String s : stringArrayList) {
//            System.out.println(s);
//        }
        // Leerzeichen sind jetzt schon raus
        // Auf 6 Zeichen prüfen
        ArrayList<String> valueList = new ArrayList<>();
        for (String s : stringArrayList) {
            if (s.length() > 6) {
                valueList.add(s);
            }
        }

//        System.out.println(valueList.toString());

        char[] tempCharArray = valueList.toString().toCharArray();
        for (char c : tempCharArray) {
            if (c == '[' || c == ']' || c == ' ') {
                // mach nichts
//                System.out.println("treffer");
            } else {
                fileWriter.write(c);
//                System.out.println("schreiben");
            }
        }
        bufferedReader.close();
        fileWriter.close();
    }
}
:)
0
Lisa
Level 41
27 Januar 2022, 15:20Lösung
Maybe cause you remove all [ and ] ??? Instead of lines 51-60 you could try
String s = valueList.toString();
fileWriter.write(s.substring(1, s.length() - 1).replaceAll(" ", ""));
// or just that one line
fileWriter.write(String.join(",", valueList));
That just removes the leading and trailing brackets that List.toString introduced. Or you use one of the variants I showed you above ;)
+2
fullTimeAdventurer Team Lead
27 Januar 2022, 18:56
okay, yes that make sense, understand. Thanks a lot <3
+1
Lernen
  • Registrierung
  • Java-Kurs
  • Hilfe zu Aufgaben
  • Preise
  • Spieleprojekte
  • Java Syntax
Community
  • Benutzer
  • Artikel
  • Forum
  • Chat
  • Erfolgsstorys
  • Aktivität
  • Affiliate Program
Unternehmen
  • Über uns
  • Kontakt
  • Rezensionen
  • Medien
  • CodeGym im Bildungsbereich
  • FAQ
  • Support
CodeGym CodeGym ist ein Java-Tutorial zum Lernen von Java von Grund auf. Dieser Kurs ist perfekt dafür geeignet, Java von Beginn an zu meistern. Er enthält über 1200 Aufgaben mit Sofortüberprüfung und grundlegende Theorie zu den Java-Grundlagen. Damit auch du bei deinem Kurs erfolgreich bist, haben wir eine ganze Reihe motivierender Inhalte: Quizfragen, Programmierprojekte, Inhalte zu effizientem Lernen und zum Berufseinstieg als Java-Entwickler.
Folgen
Sprache der Oberfläche
Programmierer werden gemacht, nicht geboren © 2023 CodeGym
MastercardVisa
Programmierer werden gemacht, nicht geboren © 2023 CodeGym
This website uses cookies to provide you with personalized service. By using this website, you agree to our use of cookies. If you require more details, please read our Terms and Policy.