Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Fly
Nov 3, 2002

moral compass
I asked someone to write a Person.equals() method and got this code, which will arbitrarily break in some cases if a person is born an January 31, 2010.
code:
public boolean equals(Object o) {
    boolean retVal = false;

    // often good to use
    if (this == o)
      return true;
    if (!(o instanceof Person))
      return false;
    Person otherPerson = (Person) o;
    String aFirstName = otherPerson.getFirstName();
    String aMidName = otherPerson.getMiddeName();
    String aLastName =  otherPerson.getLastName();
    Date aDate = otherPerson.getBirthDate();
    String thisFirstName = this.getFirstName();
    String thisMidName = this.getMiddeName();
    String thisLastName =  this.getLastName();
    Date thisDate = this.getBirthDate();

    if (aDate == null) aDate = java.util.Date.valueOf( "2010-01-31" );
    if (thisDate == null) thisDate = java.util.Date.valueOf( "2010-01-31" );
    if (thisFirstName.compareToIgnoreCase(aFirstName)==0 &&
	thisMidName.compareToIgnoreCase(aMidName)==0 &&
	thisLastName.compareToIgnoreCase(aLastName)==0 &&
	thisDate.compareTo(aDate)==0)
	retVal = true;

   return retVal
  }
Is there some reason a person would pick 2010-01-31 as substitute for null? Is this from some horrible PHP/J2EE/etc. practice with which I am not familiar?
Ignore the stylistic problems for now.

Adbot
ADBOT LOVES YOU

HFX
Nov 29, 2004

Fly posted:

I asked someone to write a Person.equals() method and got this code, which will arbitrarily break in some cases if a person is born an January 31, 2010.
code:
public boolean equals(Object o) {
    boolean retVal = false;

    // often good to use
    if (this == o)
      return true;
    if (!(o instanceof Person))
      return false;
    Person otherPerson = (Person) o;
    String aFirstName = otherPerson.getFirstName();
    String aMidName = otherPerson.getMiddeName();
    String aLastName =  otherPerson.getLastName();
    Date aDate = otherPerson.getBirthDate();
    String thisFirstName = this.getFirstName();
    String thisMidName = this.getMiddeName();
    String thisLastName =  this.getLastName();
    Date thisDate = this.getBirthDate();

    if (aDate == null) aDate = java.util.Date.valueOf( "2010-01-31" );
    if (thisDate == null) thisDate = java.util.Date.valueOf( "2010-01-31" );
    if (thisFirstName.compareToIgnoreCase(aFirstName)==0 &&
	thisMidName.compareToIgnoreCase(aMidName)==0 &&
	thisLastName.compareToIgnoreCase(aLastName)==0 &&
	thisDate.compareTo(aDate)==0)
	retVal = true;

   return retVal
  }
Is there some reason a person would pick 2010-01-31 as substitute for null? Is this from some horrible PHP/J2EE/etc. practice with which I am not familiar?
Ignore the stylistic problems for now.
I will say they are dumb. There is actually quite a bit in that code I find questionable.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

HFX posted:

I often have to work with implementing network based protocols in Java. Java's lack of unsigned type can make this a lot harder then it should be.

The syntactic sugar isn't a huge bonus to me as I often design my code to prevent the need for such checks except in a few areas.

Items I would like Java to add:

  • Proper tail recursion handled by the VM. I'm a huge fan of functional languages.
  • Operator overloading. This can be terrible or great depending on programmer usage. I have certainly seen it abused.
  • True multiple inheritance so I can quit having to add interfaces which simply invoke a member instance which implements the interface. I guess an IDE could do this automatigically for me though so its not a big issue. Does bring about other issue though.
  • Finally, I'd like a method for notification of a garbage collections. This would allow me to cache unneeded objects in certain data structures and release them if the system needs memory.

We might be getting proper tail calls. I believe the JSR-292 defines them (part of the invokedynamic stuff, also known as MLVM)

in fact:
http://wikis.sun.com/display/mlvm/TailCalls

YES.

1337JiveTurkey
Feb 17, 2005

As far as I know using a date which could even remotely be construed as valid to stand in as an invalid date or null date is never considered a good practice. new Date(Long.MIN_VALUE) would be several hundred MYA. In this case just using null would do the exact same thing you're expecting.

Fly
Nov 3, 2002

moral compass

HFX posted:

I will say they are dumb. There is actually quite a bit in that code I find questionable.
Other questions I asked had answers cut and pasted directly from places like Stackoverflow.com. :ughh: I just wonder where he cribbed that particular wrong answer.

StickFigs
Sep 5, 2004

"It's time to choose."
I'm trying to make a simple program to read a .txt file line-by-line from a file called "input.txt" then check a file "output.txt" line-by-line to see if that line already exists or not and if it doesn't then print that line into "output.txt" and repeat for every line in "input.txt"

The problem I ran into is this worked fine until I tried to read AND write to "output.txt" at the same time, the result is a blank "output.txt" file.

Anyways here is the code:

code:
import java.io.*;

public class URLChecker 
{
	public static void main(String[] args) 
	{
		//Variables
		int matches = 0;
		int removed = 0;
		String readFrom = "url_list.txt";
		String writeTo = "output.txt";
		
		try
		{
			BufferedReader inputStreamGet = new BufferedReader(new FileReader(readFrom));
			BufferedReader inputStreamCheck = new BufferedReader(new FileReader(writeTo));
			
			String get = inputStreamGet.readLine();
			String check;
			
			PrintWriter outputStream = null;
			
			try
			{
				outputStream = new PrintWriter(new FileOutputStream(writeTo));
			}
			catch (FileNotFoundException e)
			{
				System.out.println("Error opening the file " + writeTo +".");
				System.exit(0);
			}
			
			while (get != null)
			{
				check = inputStreamCheck.readLine();
				System.out.println(check);
				
				do
				{
					if (get.equals(check))
					{
						System.out.println(get + " matched with " + check);
						matches++;
					}
					
					check = inputStreamCheck.readLine();
				} while (check != null);
				
				if (matches == 0)
				{
					outputStream.println(get);
				}
				else
				{
					removed++;
				}
				
				matches = 0;
				
				get = inputStreamGet.readLine();
				
				inputStreamCheck.close();
				inputStreamCheck = new BufferedReader(new FileReader(writeTo));
			}
			
			outputStream.close();
			
			System.out.println("Job completed. Removed "+ removed +" duplicates.");
		}
		catch(Exception e)
		{
			e.printStackTrace();
	    }
	}
}
I'm pretty clueless as to how Java writes and reads files so I assume I'm trying to do something impossible, I don't know.

HFX
Nov 29, 2004
You are running on Windows. On windows you can't and read and write to the same name at the same time. You'd have to read the contents of the whole file in and then write back to that file. Another options is to write to a temporary file and then move it to the old files name and location.


In the unix world, this would work only because of how unix deals with files.

Actually, I should say you can write into the same file, but the way your program works it will not work this way. You would use the RandomAccessFile class to do this.

HFX fucked around with this message at 22:44 on Apr 17, 2009

StickFigs
Sep 5, 2004

"It's time to choose."

HFX posted:

You are running on Windows. On windows you can't and read and write to the same name at the same time. You'd have to read the contents of the whole file in and then write back to that file. Another options is to write to a temporary file and then move it to the old files name and location.

Since a temporary file won't work since I would also need to read from the temp file, how would I go about doing your first solution?

HFX posted:

Actually, I should say you can write into the same file, but the way your program works it will not work this way. You would use the RandomAccessFile class to do this.

Would someone who is new to Java be able to manage this solution?

1337JiveTurkey
Feb 17, 2005

Honestly unless your output file is going to be absolutely MASSIVE, stick them into a LinkedHashSet<String> and just iterate through that when the input file is empty.

ndb
Aug 25, 2005

1337JiveTurkey posted:

Honestly unless your output file is going to be absolutely MASSIVE, stick them into a LinkedHashSet<String> and just iterate through that when the input file is empty.

Out of curiousity, why do you recommend a LinkedHashSet rather than some other data structure?

HFX
Nov 29, 2004
Not as clean as it could be:
code:
public void removeDuplicateLines(String inputFile1, String inputFile2) throws IOException {
		Set<String> inputFile1Contents = getFileContents(inputFile2);
		inputFile1Contents = removeDuplicatedLines(inputFile1Contents, inputFile1);
		outputLines(inputFile1Contents, inputFile2);
	}
	
	private void outputLines(Set<String> inputFile1Contents, String file) throws IOException {
		PrintWriter writer = new PrintWriter(new FileWriter(file));
		for(String outputLine : inputFile1Contents) {
			writer.println(outputLine);
		}
		writer.close();	
	}
	
	
	private Set<String> removeDuplicatedLines(Set<String> lines, String inputFile2) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(inputFile2));
		String inputLine = null;
		while ((inputLine = reader.readLine()) != null) {
			if (lines.contains(inputLine)) {
				lines.remove(inputLine);
			}
		}
		reader.close();
		return lines;
	}
	
	
	private Set<String> getFileContents(String file) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(file));
		Set<String> linesFromFile = new LinkedHashSet<String>();
		String inputLine = null;
		while((inputLine = reader.readLine()) != null) {
			linesFromFile.add(inputLine);
		}
		return linesFromFile;
	}
That will remove any duplicate lines from the output and only give you the contents of output. It preserves the ordering of outputFile. If you want to make it include all non duplicates from both change the check that it no longer removes if it contains and adds to the set it doesn't contain it. Took 17 minutes, so round that up to 20. Should I charge you my wages, or what my company charges?

HFX fucked around with this message at 00:18 on Apr 18, 2009

1337JiveTurkey
Feb 17, 2005

Clock Explosion posted:

Out of curiousity, why do you recommend a LinkedHashSet rather than some other data structure?

LinkedHashSet enforces uniqueness while preserving the insertion order. It gives the exact same effect as searching through the output file every single iteration without the cost of O(n^2) IO operations.

edit: Instead, there'd be O(n) IO operations and the hashset accesses won't even show up on a profiler.

StickFigs
Sep 5, 2004

"It's time to choose."

1337JiveTurkey posted:

LinkedHashSet enforces uniqueness while preserving the insertion order. It gives the exact same effect as searching through the output file every single iteration without the cost of O(n^2) IO operations.

edit: Instead, there'd be O(n) IO operations and the hashset accesses won't even show up on a profiler.

So if I use a LinkedHashSet then it automatically forces unique entries and when I output the set to a .txt file it will be in the same order as the input .txt sans-duplicates?

HFX
Nov 29, 2004

StickFigs posted:

So if I use a LinkedHashSet then it automatically forces unique entries and when I output the set to a .txt file it will be in the same order as the input .txt sans-duplicates?

Yep. A set enforces uniqueness. That is why I used it. The iterator you get from it is guaranteed to be in order or insertion. See my code.

StickFigs
Sep 5, 2004

"It's time to choose."

HFX posted:

Yep. A set enforces uniqueness. That is why I used it. The iterator you get from it is guaranteed to be in order or insertion. See my code.

I'm having a little trouble understanding your code, right now I'm trying to figure out how you output the populated LinkedHashSet to the .txt file. Looking at it now I see:

code:
for(String outputLine : inputFile1Contents) {
			writer.println(outputLine);
		}
I don't understand anything about that snippet of code except for just "writer.println(outputLine);", but I don't understand how outputLine gets a value or anything. (I guess it's probably because I don't understand the ":" usage there since it doesn't look like an if-else statement.)

StickFigs fucked around with this message at 01:02 on Apr 18, 2009

1337JiveTurkey
Feb 17, 2005

HFX posted:

Yep. A set enforces uniqueness. That is why I used it. The iterator you get from it is guaranteed to be in order or insertion. See my code.

Er, why bother with the removeDuplicatedLines() method then?

PnP Bios
Oct 24, 2005
optional; no images are allowed, only text
any decent modern java decompilers?

1337JiveTurkey
Feb 17, 2005

StickFigs posted:

I'm having a little trouble understanding your code, right now I'm trying to figure out how you output the populated LinkedHashSet to the .txt file. Looking at it now I see:

code:
for(String outputLine : inputFile1Contents) {
			writer.println(outputLine);
		}
I don't understand anything about that snippet of code except for just "writer.println(outputLine);", but I don't understand how outputLine gets a value or anything. (I guess it's probably because I don't understand the ":" usage there since it doesn't look like an if-else statement.)

That's foreach. It's a for loop which will go through every single item in a set, list, array or anything else that implements Iterator<T>. It automatically sets outputLine every time it loops through and terminates when it runs out of items.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
Iterable<T>

StickFigs
Sep 5, 2004

"It's time to choose."

1337JiveTurkey posted:

That's foreach. It's a for loop which will go through every single item in a set, list, array or anything else that implements Iterator<T>. It automatically sets outputLine every time it loops through and terminates when it runs out of items.

Ok I got my code to work how I wanted it to:

code:
import java.io.*;
import java.util.LinkedHashSet;
import java.util.Set;

public class URLChecker
{
	public static void main(String[] args) 
	{
		//Variables
		int initialCount = 0;
		int finishedCount = 0;
		String readFrom = "input.txt";
		String outputTxt = "output.txt";
		
		try
		{
			BufferedReader inputStreamCheck = new BufferedReader(new FileReader(readFrom));
			
			String check;
			
			PrintWriter outputStream = null;
			
			Set<String> setlink = new LinkedHashSet<String>();
			
			check = inputStreamCheck.readLine();
			
			while (check != null)
			{
				initialCount++;
				
				check = inputStreamCheck.readLine();
			}
			
			inputStreamCheck.close();
			
			inputStreamCheck = new BufferedReader(new FileReader(readFrom));
			
			check = inputStreamCheck.readLine();
			
			while (check != null)
			{
				setlink.add(new String(check));
				
				check = inputStreamCheck.readLine();
			}
			
			try
			{
				outputStream = new PrintWriter(new FileOutputStream(outputTxt));
			}
			catch (FileNotFoundException e)
			{
				System.out.println("Error opening the file " + outputTxt +".");
				System.exit(0);
			}
			
			for(String outputLine : setlink) 
			{
				outputStream.println(outputLine);
			}
			
			outputStream.close();
			
			int removed = (initialCount - setlink.size());
			
			System.out.println("Job completed. Removed "+ removed +" duplicates.");
		}
		catch(Exception e)
		{
			e.printStackTrace();
	    }
	}
}
The only problem is I still don't understand the for-each loop, I found this page which explains it but I still don't understand exactly what is going on, especially where it says the first example should be read as “for each TimerTask t in c.”

StickFigs fucked around with this message at 02:47 on Apr 18, 2009

ynef
Jun 12, 2002

StickFigs posted:

The only problem is I still don't understand the for-each loop, I found this page which explains it but I still don't understand exactly what is going on, especially where it says the first example should be read as “for each TimerTask t in c.”

Say that you have some collection of values: a list, an array, a hash set... any collection (that implements the interface Iterable<T>). It is very common to iterate over every element in this collection and do something with each element. Previously, we had to write code like this:

code:
for (int i=0; i<someArray.length; i++) {
  // do stuff to someArray[i]
}
But see, that's what the code looks like for an array. If you want to iterate over a list, you had to write:

code:
for (int i=0; i<someList.size(); i++) {
  // do stuff to someList.get(i)
}
...and there were other variations for various other data structures that all had in common that they held a bunch of values, and we would like to iterate over these values in sequence. Stupid, right?

So now we have a new type of for-loop that does just what we want: it allows us to write code that looks the same no matter which underlying data structure is used, because it solves the same basic problem. It basically says: iterate over the entire collection, and give me a reference to the current element so I can do something with it. It looks as follows:

code:
for (ElementType currentElement : collectionOfElements) {
  // do stuff to currentElement
}
where "ElementType" is the type of elements stored in collectionOfElements (such as String, or Integer). Not only does this give us a bit cleaner code (no indexes all over the place), but it also means that we can easily switch what kind of collection we're using to store these elements without breaking our for-loops (recall the difference between the array and list iterator loops above). And because all that is required from a data structure to be used in this way is that it implements a certain interface, Iterable<T>, you can make your own data structures compatible with this clever type of loop.

StickFigs
Sep 5, 2004

"It's time to choose."
Ah thank you, I was confused because I didn't know if it always reassigned a value to the current place in a collection or not or if it also did some other stuff behind the scenes. So I guess basically I really don't need to know what its doing behind the scenes, just what I'll end up with.

HFX
Nov 29, 2004
The removal was if he wanted to remove all duplicate lines and keep just the unique lines.

As to for the foreach. We used to use while loops to go through a collection using an iterator. If you ever go through an entire Collection, iterators are often your best friend, and this includes an array list. It keeps assigning the next value of the iterator to the declared variable until no more are available.

In fact, my code won't actually work. It will throw an exception at run time do to the way I removed it. That is what you get for trying to rush out a reply before you are going out.

Boo This Man
Mar 25, 2008

As I was looking over my notes for my Java final. It has a question about out of bounds. I already know the answer, but what makes an array index Out-of-bounds?

HFX
Nov 29, 2004

Logostomp posted:

As I was looking over my notes for my Java final. It has a question about out of bounds. I already know the answer, but what makes an array index Out-of-bounds?

It is a negative number or it is higher then the size allocated for the array.
Examples:

myArray[-1]; is out of bounds.


int myArray = new int[10];
myArray[10]; is out of bounds since Java is 0 indexed.

sd6
Jan 14, 2008

This has all been posted before, and it will all be posted again
I'm having problems with servlets in Ubuntu. I'm trying to add the servlet-api.jar file from Tomcat to Java, so I added this line:
code:
CLASSPATH="/Desktop/apache-tomcat-6.0.18/lib/servlet-api.jar:."
to etc/environment and restarted. But when I try to javac my file, I still get error messages saying that javax.servlet and the like don't exist. What did I do wrong?

UR MR GAY
Oct 26, 2007
I'm using the scanner class with a line separator as the delimiter to parse an obj file. The scanner won't detect any line separators until i manually open the file in WordPad and add just one. So my question is, how can I circumvent that?

ynef
Jun 12, 2002

fge posted:

I'm having problems with servlets in Ubuntu. I'm trying to add the servlet-api.jar file from Tomcat to Java, so I added this line:
code:
CLASSPATH="/Desktop/apache-tomcat-6.0.18/lib/servlet-api.jar:."
to etc/environment and restarted. But when I try to javac my file, I still get error messages saying that javax.servlet and the like don't exist. What did I do wrong?

1. You need to write "export" first on that line.
2. That folder name is wrong: your desktop is at "/home/yourUserName/Desktop/".
3. And you don't want to replace your classpath like that (you should probably just append to it, like so: export CLASSPATH="$CLASSPATH:/more/stuff/here:/even/more/stuff").

Also, don't put stuff like this in /etc/environment. Put it in your ~/.bashrc, or make a script that exports such variables for you that you run as a setup before running javac/java.

ynef
Jun 12, 2002

UR MR GAY posted:

I'm using the scanner class with a line separator as the delimiter to parse an obj file. The scanner won't detect any line separators until i manually open the file in WordPad and add just one. So my question is, how can I circumvent that?

Can you explain what you are trying to do (there may be a better way) and also posting a sample OBJ file that you are working with?

A possible cause of the problem could be related to Windows and UNIX treating line separators differently, but I think Scanner is smart enough to handle such things on its own.

UR MR GAY
Oct 26, 2007

ynef posted:

Can you explain what you are trying to do (there may be a better way) and also posting a sample OBJ file that you are working with?

A possible cause of the problem could be related to Windows and UNIX treating line separators differently, but I think Scanner is smart enough to handle such things on its own.

Well, I'm trying to retrieve all the vertex and face information from the file for an engine I'm building. Right now, I'm doing this by adding all the lines of the file into a vector and then parsing each line individually to remove all the necessarily information.

code:
private void readObj(String objPath){
            try{
               File objFile = new File(objPath);
               Scanner scanner = new Scanner(objFile);
               scanner.useDelimiter(System.getProperty("line.separator"));
               while(scanner.hasNext()){
               parsedObjFile.add(scanner.next());
               }
               scanner.close();
               parseObjVector();
            }
            catch(FileNotFoundException e){
            e.printStackTrace();
            }}
    private void parseObjVector(){
        ListIterator u = parsedObjFile.listIterator();
        while(u.hasNext()){
        parseLine(u.next().toString());
         }
As for the OBJ file, here's one directly exported out of maya: http://www.mediafire.com/download.php?lzuk5doojyw

JulianD
Dec 4, 2005
I'm currently trying to write a class which needs to implement the Comparable interface so that I can compare two strings so that I can arrange the strings alphabetically. However, I'm hitting a snag when I try to do so:

code:
public class testingcomparable implements Comparable
{
  public static void main(String[] args)
  {
    String smith, doe;
    int i;
    
    i = smith.compareTo(doe);
    
    System.out.println("Value of i is " + i);
  }
}
I wrote this class so I could play around with the compareTo method and teach myself how it works, but I keep getting the following exception:

testingcomparable is not abstract and does not override abstract method compareTo(java.lang.object) in java.lang.Comparable

When I googled the error to try to figure out what I was doing wrong, I found this:

This error is reported when a class implements an interface (in this case Comparable) but does not supply all the necessary methods or misspells a method name, or has the the wrong number or types of parameters in one of the interface methods.

I'm not really sure what that means I'm missing in my testing class, but I think I need to have the actual compareTo method in my class. However, I'm not sure how to alter it because the underlying problem is a comparison between two strings, and the only implementations of the compareTo methods I've seen compare two integers. Any ideas?

dancavallaro
Sep 10, 2006
My title sucks
Your class doesn't need to implement Comparable if all you want to do is use the compareTo method of another object. You only need to add "implements Comparable" and create a compareTo method if you want *your class* to be able to be compared to other instances of your class.

JulianD
Dec 4, 2005
I should provide some more information, then. My overarching project is to design a program which uses a doubly linked list whose nodes are instances of a cruise ADT. Each cruise ADT contains an instance of a passenger ADT, which is a singly linked list of passengers, linked in alphabetical order. So effectively I'm going to be comparing instances of my Passenger class to other instances of my Passenger class to determine whether they are in alphabetical order. That's why my professor specifically instructed us to implement Comparable when we're writing our classes.

Mill Town
Apr 17, 2006

JulianD posted:

I should provide some more information, then. My overarching project is to design a program which uses a doubly linked list whose nodes are instances of a cruise ADT. Each cruise ADT contains an instance of a passenger ADT, which is a singly linked list of passengers, linked in alphabetical order. So effectively I'm going to be comparing instances of my Passenger class to other instances of my Passenger class to determine whether they are in alphabetical order. That's why my professor specifically instructed us to implement Comparable when we're writing our classes.

Yes, in that case, your class needs to actually implement compareTo. Implement it and that error will go away. Then you need to figure out how you want the compareTo method for people to actually work, which seems to be your sticking point. Think about exactly what it means for one person's name to come alphabetically after another.

JulianD
Dec 4, 2005

Mill Town posted:

Yes, in that case, your class needs to actually implement compareTo. Implement it and that error will go away. Then you need to figure out how you want the compareTo method for people to actually work, which seems to be your sticking point. Think about exactly what it means for one person's name to come alphabetically after another.

Right, I understand that, but I cannot think for the life of me how I would do that. The only ways I know of to compare two strings are the compareTo method, which I need to alter, and the .equals operator, which will only check one of three different cases. If I have say, smith.compareTo(doe), it should return a value of 1; if I have smith.compareTo(smith), it should return a value of 0 (which is where I could use the .equals operator); and if I have doe.compareTo(smith), it should return a value of -1. The problem is the actual comparison of doe to smith or vice-versa.

Mill Town
Apr 17, 2006

JulianD posted:

Right, I understand that, but I cannot think for the life of me how I would do that. The only ways I know of to compare two strings are the compareTo method, which I need to alter, and the .equals operator, which will only check one of three different cases. If I have say, smith.compareTo(doe), it should return a value of 1; if I have smith.compareTo(smith), it should return a value of 0 (which is where I could use the .equals operator); and if I have doe.compareTo(smith), it should return a value of -1. The problem is the actual comparison of doe to smith or vice-versa.

You can write the compareTo method for your class such that it calls the existing compareTo method in the string class to do most of the work. Then you just have to figure out how to handle first and last names - this is what I was hinting at when I said "Think about exactly what it means for one person's name to come alphabetically after another."

I suggest making a list of different names on paper and working out exactly what compareTo should return for each pair of names. Then just write the compareTo function so it does in code the equivalent of what you've been doing on paper.

Really, if I tell you anything more, I'll just be giving away the whole answer.

UR MR GAY
Oct 26, 2007

JulianD posted:

Right, I understand that, but I cannot think for the life of me how I would do that. The only ways I know of to compare two strings are the compareTo method, which I need to alter, and the .equals operator, which will only check one of three different cases. If I have say, smith.compareTo(doe), it should return a value of 1; if I have smith.compareTo(smith), it should return a value of 0 (which is where I could use the .equals operator); and if I have doe.compareTo(smith), it should return a value of -1. The problem is the actual comparison of doe to smith or vice-versa.

If you can't think of a way to compare two strings, can you build a function that maps every string(if not a string, perhaps a character array?) to a unique number that has the property you're looking for?

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

To add what Mill Town said, from looking at your code snippit I don't think you know what an interface really is. Think of it as a template for functions for your code. When you implement the interface you must include your implementation of those methods in your code.

Look at the jdoc for Comparable ( http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html ). You see how the only method listed is 'int compareTo(T o)'? That means you must must include a method called compareTo that returns an int somewhere in your code.

That is why you are getting the exception.



As for how to implement the function, nobody is going to do your homework but here is a hint. What primitive type makes up a String object? And what other kind of primitive type can it be represented as?

Mill Town
Apr 17, 2006

dvinnen posted:

As for how to implement the function, nobody is going to do your homework but here is a hint. What primitive type makes up a String object? And what other kind of primitive type can it be represented as?

He doesn't even need to get that dirty, there's a perfectly good compareTo function already in String that he can use to do the dirty work...

Adbot
ADBOT LOVES YOU

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

Mill Town posted:

He doesn't even need to get that dirty, there's a perfectly good compareTo function already in String that he can use to do the dirty work...

yea, i know that of course, but judging by the fact that the instructor wants him to implement the Comparable interface I think he is suppose to roll his own

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply