I have the following assignment for my Java class, and, as my professor fully supports reaching out for assistance and advice, I will ask all of you here. This is my second formal class for Java, and I have made a few pointless Android apps, so I'm not a total beginner, but I know I am missing something.
and the code I have so far:Quote:
Create an original single-file program in a file called <YourName>Week3TreeLab.java that satisfies this criteria:
STRUCTURE CRITERIA
1. Your class includes a constructor that takes a string as a parameter. (Lets call that string the "one_letter" for this discussion.)
2. Your class implements the Comparable interface such that it compares the "one_letter" given to it via the constructor.
OTHER CRITERIA
3. The main method of your class Prints your full name (First and Last)
4. The main method of your class creates an instance of itself for each letter of your last name and each created instance is stored in a TreeSet.
5. The main method of your class prints the "one_letter" of each instance stored in the TreeSet by walking the TreeSet via a "Iterator<T>" style iterator, where <T> is your classname.
I know that the line "x[i] = new MyNameWeek3Lab(Character.toString(name.charAt(i))) ;" is causing my problems, I had it not using an array, but it was only picking up the last letter ie the "e". I can get the proper output, but not in the way the professor wants. I hate that I can't just do it how it makes sense to me!Code:import java.util.*;
public class MyNameWeek3Lab implements Comparable {
public static String l;
public static TreeSet<MyNameWeek3Lab> t1 = new TreeSet<MyNameWeek3Lab>();
public static String letter;
public MyNameWeek3Lab(String letter){
l = letter;
}
public static void printTree(){
//Prints TreeSet
Iterator<MyNameWeek3Lab> it1 =t1.iterator();
while(it1.hasNext()){
MyNameWeek3Lab entry = it1.next();
System.out.println(entry.l);
}
}
public static void main(String[] args) {
String name = "My Name";
System.out.println("Week 3 Lab, " + name);
name = name.toLowerCase();
//add letters to treeset via constructor
int i;
MyNameWeek3Lab[] x = new MyNameWeek3Lab[0];
for(i=0; i < name.length(); i++){
x[i] = new MyNameWeek3Lab(Character.toString(name.charAt(i)));
t1.add(x[i]);
}
//compare
//print with iterator
printTree();
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
Should I not use an array? Do I just need to write the compareTo first? Could I get some help with the compareTo? I feel it is unnecessary since TreeSet sorts automatically, and I have never used compareTo for anything other than integers, so I'm not sure how to approach it for strings.
And am I meeting the requirements, anything you can think of to get me closer?
any and all input is appreciated.
