Reputation: 193
I'm new to Java and the first to use vector.
input
A aaa bbb
C dddd eeee fff
when you want to vec.elementAt(1);
The output will be:
C ddd eee fff
I don't know how to use two vectors(name and word) implement it.
My thoughts are like this:
vec[0] vec[1]
name A C
word aaa bbb dddd eeee ffff
wvec[0] wvec[1] wvec[0] wvec[1] wvec[2]
I have been thinking about this problem for a week
This is my code:
public class Name {
Vector <String> name = new Vector<String>();
....
while ( ... ) {
vec.add(name);
...
} // while
}
public class Word {
Vector <String> wvec = new Vector<String>();
while ( ... ) {
wvec.add(word);
} // while
}
Upvotes: 1
Views: 100
Reputation: 19545
Example implementation which parses string lines and prints data may be as follows:
import java.util.*;
public class Example {
static class Line {
private String name;
private Vector<String> words = new Vector<>();
public void setName(String name) { this.name = name; }
public void addWord(String word) { this.words.add(word); }
public String getName() { return name; }
public Vector<String> getWords() { return words; }
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("name:\t").append(name).append('\n');
sb.append("words:\t");
for (String word : words) {
sb.append(word).append('\t');
}
sb.append("\n \t");
for (int i = 0, n = words.size(); i < n; i++) {
sb.append("w[").append(i).append("]\t");
}
sb.append('\n');
return sb.toString();
}
}
private static Line parseLine(String src) {
if (src == null) return null;
Line line = new Line();
String[] arr = src.split(" ");
if (arr.length > 0) {
line.setName(arr[0]);
for (int i = 1; i < arr.length; i++) {
line.addWord(arr[i]);
}
}
return line;
}
public static void main(String []args) {
String[] rawLines = {
"A aaa bbb",
"C dddd eeee fff"
};
Vector<Line> lines = new Vector<>();
for (String rawLine : rawLines) {
Line line = parseLine(rawLine);
lines.add(line);
System.out.println(line);
}
}
}
This code prints the following output:
name: A
words: aaa bbb
w[0] w[1]
name: C
words: dddd eeee fff
w[0] w[1] w[2]
Upvotes: 0
Reputation: 3345
You can achieve the scenario like below:
Word Class:
class Word{
char name;
Vector<String> words;
}
TestClass:
public class TestClass { public static void main(String[] args) {
Word word = new Word();
word.name = 'A';
word.words = new Vector<String>();
word.words.add("aaa");
word.words.add("bbb");
Word word1 = new Word();
word1.name = 'B';
word1.words = new Vector<String>();
word1.words.add("dddd");
word1.words.add("eeee");
word1.words.add("fff");
Vector<Word> wordVector = new Vector<>();
wordVector.add(word);
wordVector.add(word1);
System.out.println("Name" + "-----" + "Words");
for (int i = 0; i < wordVector.size(); i++) {
System.out.print(wordVector.get(i).name + "------");
for(int j=0;j<wordVector.get(i).words.size();j++) {
System.out.print(wordVector.get(i).words.get(j)+" ");
}
System.out.println();
}
}
}
Upvotes: 1