In Java: Write a class encapsulating the concept of an HTML page, assuming an HT
ID: 3875641 • Letter: I
Question
In Java: Write a class encapsulating the concept of an HTML page, assuming an HTML statement has only a single attribute: the HTML code for the page. Include a constructor, the accessors and mutators, and methods toString and equals. Include the following methods: one checking that there is a > character following each < character, one counting how many images are on the page (i.e., the number of IMG tags), and one counting how many links are on the page (i.e., the number of times we have “A HREF”). Write a client class to test all the methods in your class.
Provide a sample output.
Explanation / Answer
import java.util.Objects;
/**
*
* @author sambh
*/
public class HTML {
private String code;
public HTML(String code) {
this.code = code;
}
public HTML() {
this.code = "";
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "HTML{" + "code=" + code + '}';
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final HTML other = (HTML) obj;
if (!Objects.equals(this.code, other.code)) {
return false;
}
return true;
}
public boolean checkCode() {
boolean start = false;
for (int i = 0; i < code.length(); i++)
if (start) {
if (code.charAt(i) == '<')
return false;
else if (code.charAt(i) == '>')
start = false;
}
else {
if (code.charAt(i) == '<')
start = true;
else if (code.charAt(i) == '>')
return false;
}
return true;
}
public int countImg() {
if (!checkCode())
return 0;
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = code.indexOf("<img",lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += "<img".length();
}
}
return count;
}
public int countHref() {
if (!checkCode())
return 0;
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = code.indexOf("<a href",lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += "<a href".length();
}
}
return count;
}
}
class HTMLTester {
public static void main(String[] args) {
HTML html = new HTML();
html.setCode("<head><title>ABC</title></head>"
+ "<body>"
+ " <a href="mailto:someone@example.com?cc=someoneelse@example.com&bcc=andsomeoneelse@example.com" +
"&subject=Summer%20Party&body=You%20are%20invited%20to%20a%20big%20summer%20party!">Send mail!</a>"
+ "<p>"
+ " <img src="img_girl.jpg" alt="Girl in a jacket">"
+ "<p>"
+ " <img src="img_chania.jpg" alt="Flowers in Chania">"
+ "</body>");
System.out.println(html);
System.out.println("# of imgs: " + html.countImg());
System.out.println("# of hrefs: " + html.countHref());
}
}
Here you go champ!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.