At the moment, I'm solving the following problem: I need to implement a public static buildDefinitionList() method that generates an HTML list of definitions (tags <dl>, <dt> and <dd>) and returns the resulting string. If there are no elements in the array, the method returns an empty string.
The method takes as input a list of definitions in the form of a two-dimensional array:
String[][] definitions = {
{"definition1", "description1"},
{"definition2", "description2"},
};
That is, each element of the input array is itself an array containing two elements: a term and its definition.
String[][] definitions = {
{"Bulb", "Bulge, thickening on the surface of something"},
{"Beaver", "An animal from the order of rodents"},
};
HtmlBuilder.buildDefinitionList(definitions);
// "<dl><dt>Bulb</dt><dd>Bulge, thickening on the surface of something</dd><dt>Beaver</dt><dd>An animal from the order of rodents</dd></dl>";
Here is my code:
package com.arrays.problem6;
public class HtmlBuilder {
public static void main(String[] args) {
}
public static String buildDefinitionList(String[][] definitions){
var result = new StringBuilder();
result.append("<dl><dt>");
for (var item : definitions) {
result.append("<dd>");
result.append(item);
result.append("</dl></dd>");
}
result.append("</dl></dd>");
return result.toString();
}
}
The program is working in the right direction, but so far I can not find the error. Please help me find it.
Still, I had to figure it out on my own. I didn’t need nested loops. It’s all about creating two additional string variables that are written to a two-dimensional array. Well, I also needed the same check for the absence of elements in the array.
public class HtmlBuilder {
public static void main(String[] args){
}
public static String buildDefinitionList(String[][] definitions){
if(definitions.length==0){
return "";
}
StringBuilder result = new StringBuilder();
result.append("<dl>");
for(String[] definition : definitions){
String name=definition[0];
String description=definition[1];
result.append("<dt>");
result.append(name);
result.append("</dt>");
result.append("<dd>");
result.append(description);
result.append("</dd>");
}
result.append("</dl>");
return result.toString();
}
}
Related
so I have a recursive program where I am trying to generate all the permutations of a String. I intend to store the permutations in a list of list called ans.
Every single current permutation is stored in the container list which is used to populate the ans list. I am suspecting , since list is a reference type so maybe I am loosing the values in ans list because the container list is getting manipulated? Am I an idiot
import java.util.*;
public class practice_3 {
static String str="abc";
static List<List<Character>> ans=new ArrayList<List<Character>>();
public static void permString(ArrayList container )
{
if(container.size()==str.length())
{System.out.println(container);
ans.add(container);
return;
}
for(int i=0;i<str.length();i++)
{
if(!container.contains(str.charAt(i)))
{
container.add(str.charAt(i));
permString(container);
container.remove(container.size()-1);
}
}
}
public static void main(String[] args) {
ArrayList<Character> container=new ArrayList<>();
permString(container);
System.out.println(ans);
System.out.println("container end="+container);
}
}
You are correct, as container was passed by reference the changes made in container from point to point reflects within ans (Collection of Collection) as well.
To avoid this, you need to clone / create a new copy of the container at the time of storing into the ans collection. This can be easily achieved by following.
ans.add(new ArrayList<Character>(container));
I'm having trouble understanding what exactly I would put in one of my classes to create the add method for 3 Arrays of the same Type. Here are the generic arrays in the main class
ArrayContainer<Integer> numberContainer = new ArrayContainer<>();
ArrayContainer<String> wordContainer = new ArrayContainer<>();
ArrayContainer<Pokemon> pokedex = new ArrayContainer<>();
My constructor for ArrayContainer is
public ArrayContainer(){
container = (T[]) new Object[defaultSize];
numItems = 0;
}
In my separate class, I'm confused what to put for my
public void add (T item){}
and I'm confused as what to return within my toString. I know you add to an array by putting
arrayName[index] = whatever;
But what would I put in that add method that would add to whatever array I call the method on? Would it be container[index] = item;?
What should I return that would return the element in the array?
Since the number of items in your ArrayContainer is not known beforehand, you should use a dynamic array, also known as List.
The numItems then becomes redundant since you can get it by calling list.size()
Your add function will only need to call list.add. As noted in the comments, it seems you're re-writing/wrapping List
In your toString method, you can return a string that concatenates all results of toString of the items included. StringBuilder can help you create a "format" that suits you. Of course this means that the objects you're putting in the container need to implement toString
Combining all the things will give you something like this:
ArrayContainer
public class ArrayContainer<T> {
private List<T> items;
public ArrayContainer() {
items = new ArrayList<>();
}
public void add(T item) {
items.add(item);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (T it: items)
sb.append(it.toString()).append(' ');
sb.append(']');
return sb.toString();
}
}
Main
public class Main {
public static void main(String[] args) {
ArrayContainer<String> stringArrayContainer = new ArrayContainer<>();
stringArrayContainer.add("hello");
stringArrayContainer.add("world");
System.out.println(stringArrayContainer);
// Outputs: [hello world]
}
}
I am new to java and am doing a programming challenge and just can't seem to understand what is meant by:
Uses two for loops to put all the words from this (remember, you will be executing this method inside a WordGroup object) and the parameter WordGroup into the HashSet.
(presume this refers to one of my WordGroups.)
I have seen other examples of for loops being used to to store objects, but I have never done this personally. I've only ever used a for loop to iterate through the an array list and print out a list of variables before. I'm not sure how I would write this for loop out to carry out this instruction. Here is the code:
WordGroup class
package lab5;
import java.util.HashSet;
public class WordGroup {
String word;
//Creates constructor which stores a string value in variable "word" and converts this into lower case using the lower case method.
public WordGroup(String aString) {
this.word = aString.toLowerCase();
}
public String[] getWordArray() {
String[] wordArray = word.split("-");
return wordArray;
}
public String getWordSet(WordGroup secondWordGroup) {
HashSet<String> newHashSet = new HashSet<>();
for (WordGroup x : secondWordGroup) {
newHashSet.put(x);
}
}
}
Main class
package lab5;
public class Main{
public static void main (String[] args) {
WordGroup firstWordGroup = new WordGroup("You-can-discover-more-about-a-person-in-an-hour-of-plau-tban-in-a-year-of-conversation");
WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");
System.out.println("*****First Array list*****");
String[] firstWordArray = firstWordGroup.getWordArray();
for( String word : firstWordArray) {
System.out.println(word);
}
System.out.println("*****Second Array list*****");
String[] secondWordArray = secondWordGroup.getWordArray();
for( String word : secondWordArray) {
System.out.println(word);
}
}
}
If anybody could help a beginner out on what is meant by this and how to implement this, that would be very helpful and much appreciated by myself and possibly others who may have the same issue. Thanks. P.S. I know my for loop is completely wrong but I wanted to at least attempt it rather than asking for help without actually trying myself.
It's a little bit unclear, but I'm assuming that getWordSet should return the set of words that are in both the WordGroup object that you call on, and the WordGroup that you give as input. So if wg1 has the words "a" and "b", and wg2 has the words "b" and "c", then wg1.getWordSet(wg2) returns the set containing the words "a", "b", "c".
To accomplish this, you will want to do something like this:
HashSet<String> newHashSet = new HashSet<>();
for (String word : secondWordGroup.getWordArray())
newHashSet.add(word);
for (String word : this.getWordArray())
newHashSet.add(word);
Does anybody know why i can't append a char to this StringBuffer array (in my example below) and can somebody please show me how i needs to be done?
public class test {
public static void main(String args[]){
StringBuffer[][] templates = new StringBuffer[3][3];
templates[0][0].append('h');
}
}
My output to this code is:
output: Exception in thread "main" java.lang.NullPointerException
at test.main(test.java:6)
It would help me so much so if you know any solution, please respond to this
Below statement will just declare an array but will not initalize its elements :
StringBuffer[][] templates = new StringBuffer[3][3];
You need to initialize your array elements before trying to append the contents to them. Not doing so will result in NullPointerException
Add this initialization
templates[0][0] = new StringBuffer();
and then append
templates[0][0].append('h');
You need to initialize the buffers before you append something
templates[0][0] = new StringBuffer();
Others correctly pointed out the correct answer, but what happens when you try to do something like templates[1][2].append('h');?
What you really need is something like this:
public class Test { //<---Classes should be capitalized.
public static final int ARRAY_SIZE = 3; //Constants are your friend.
//Have a method for init of the double array
public static StringBuffer[][] initArray() {
StringBuffer[][] array = new StringBuffer[ARRAY_SIZE][ARRAY_SIZE];
for(int i = 0;i<ARRAY_SIZE;i++) {
for(int j=0;j<ARRAY_SIZE;j++) array[i][j] = new StringBuffer();
}
return array;
}
public static void main(String args[]){
StringBuffer[][] templates = initArray();
templates[0][0].append('h');
//You are now free to conquer the world with your StringBuffer Matrix.
}
}
Using the constants are important, as is is reasonable to expect your matrix size to change. By using constants, you can change it in only one location rather then scattered throughout your program.
How do you return an array object in Java? I have an object that has an array in it and I want to work with it in my main class:
// code that does not work
class obj()
{
String[] name;
public obj()
{
name = new string[3];
for (int i = 0; i < 3; i++)
{
name[i] = scan.nextLine();
}
}
public String[] getName()
{
return name;
}
}
public class maincl
{
public static void main (String[] args)
{
obj one = new obj();
system.out.println(one.getName());
}
I am sorry if the answer is simple but I am teaching myself to code and I have no idea how you would do this.
You have to use the toString method.
System.out.println(Arrays.toString(one.getName()));
toString is a built-in function in Java (it might need library import; if you are using Netbeans, it will suggest it).
If the problem is to print it use
System.out.println(Arrays.toString(one.getName()));
//note System, not system
When you do getName() you are returning a reference to an array of strings, not the strings themselves. In order to access the individual strings entered, you can use the array index
String enteredName = name[index] format.
From your program, it looks like you want to print each item entered. For that, you could use a method like the following
public void printName() {
// for each item in the list of time
for(String enteredName : name) {
// print that entry
System.out.println(enteredName);
}
}