finished CountWordsVisitor

This commit is contained in:
Johannes Schmelz 2024-06-08 12:53:20 +00:00
parent dcf2a95b4f
commit 81ea768dca
6 changed files with 64 additions and 8 deletions

View File

@ -1,5 +1,6 @@
package uebung08.doc; package uebung08.doc;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class Book { public class Book {
@ -28,10 +29,22 @@ public class Book {
} }
public String tableOfContents() { public String tableOfContents() {
return ""; List<String> res = new ArrayList<>();
for (TextComponent textComponent : content) {
res.addAll(textComponent.accept(new TableOfContentsVisitor()));
}
return res.toString();
} }
public int countWordsByVisitor() { public int countWordsByVisitor() {
return 0; int count = 0;
for (TextComponent textComponent : content) {
count += textComponent.accept(new CountWordsVisitor());
}
return count;
} }
} }

View File

@ -2,10 +2,36 @@ package uebung08.doc;
public class CountWordsVisitor implements Visitor<Integer>{ public class CountWordsVisitor implements Visitor<Integer>{
public Integer visit(Image image) {
@Override
public <T> Integer visit(TextComponent textComponent) {
image.accept(this);
return 0; return 0;
} }
public Integer visit(Paragraph paragraph) {
int wordcount = 0;
boolean isInWord = false;
for (int i = 0; i < paragraph.getText().length(); i++) {
if(Character.isAlphabetic(paragraph.getText().charAt(i))){
if (!isInWord) {
wordcount++;
isInWord = true;
}
} else {
isInWord = false;
}
}
return wordcount;
}
public Integer visit(Section section) {
int count = 0;
for (TextComponent textComponent : section.getContent()) {
count += textComponent.accept(this);
}
return count;
}
} }

View File

@ -28,6 +28,10 @@ public class Paragraph implements TextComponent {
return wordcount; return wordcount;
} }
public String getText(){
return text;
}
@Override @Override
public <T> T accept(Visitor<T> visitor) { return visitor.visit(this); } public <T> T accept(Visitor<T> visitor) { return visitor.visit(this); }
} }

View File

@ -20,6 +20,10 @@ public class Section implements TextComponent {
return wordcount; return wordcount;
} }
public List<TextComponent> getContent() {
return content;
}
@Override @Override
public <T> T accept(Visitor<T> visitor) { return visitor.visit(this); } public <T> T accept(Visitor<T> visitor) { return visitor.visit(this); }
} }

View File

@ -0,0 +1,10 @@
package uebung08.doc;
import java.util.List;
public class TableOfContentsVisitor implements Visitor<List<String>>{
public List<String> visit(Image image) {
}
}

View File

@ -1,8 +1,7 @@
package uebung08.doc; package uebung08.doc;
public interface Visitor<T> { public interface Visitor<T> {
T visit(TextComponent textComponent);
T visit(Book book);
T visit(Paragraph paragraph); T visit(Paragraph paragraph);
T visit(Image image); T visit(Image image);
T visit(Section section); T visit(Section section);