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
hexadecimal
Nov 23, 2008

by Fragmaster
when you run your program you run it using java.exe .... some options like class path, and path to your main .class file.

just use -Xmx1000m in there, or if you are using some IDE you can go into its options and find a field that says something like "command line arguments" for when you run your project. just put -Xmx1000m there.

For exception, you must have (or should add at right place) something like

code:
catch( Exception exc )
{
    exc.printStackTrace();
}
This will print the stack trace of exception that was caught. it is very useful for debugging purposes.

Adbot
ADBOT LOVES YOU

oh no computer
May 27, 2003

Really common beginner error, never use == on Strings. Use .equals() :)

Edit: as in if (choice1.equals("yes") || choice1.equals("Yes"))

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

JulianD posted:

I checked to see that's the problem after your suggestion, but I don't think that's it. I added this to my program to see how much memory I had before and after calling the last method of my program:

code:
double freeMem;
Runtime r = Runtime.getRuntime();
freeMem = r.freeMemory();
System.out.println("free memory after creating array:  " + freeMem);
I only declared freeMem and r once; I inserted the last two lines before and after the last method of my program. In doing so, the amount of available memory before and after was 3768200.0 and 3359536.0, respectively. The program doesn't appear to be out of memory, so am I interpreting this incorrectly or is it something else causing the problem?

If you want to see how much ram is available to your vm you should run jstat on the vm running your program. You can see how much ram is available to each object space (eden, survivor 0 and 1, old gen and permanent gen) over the duration of your program's lifetime. It's a really awesome tool and comes with the jdk.

hexadecimal
Nov 23, 2008

by Fragmaster

BELL END posted:

Really common beginner error, never use == on Strings. Use .equals() :)

Edit: as in if (choice1.equals("yes") || choice1.equals("Yes"))

I would like to expand on this, saying that this is because == compares where reference points to, not the actual contents of objects. Since java has no operator overloading you have to use .equal for String's comparisons, since .equals will actually check the contents of Strings, and == only checks if its same object.

You can have String a = "zomg" and String b = "zomg". However if JVM decides to store them in different locations in memory, then a==b will return false.

Bushibytes
Sep 3, 2006
Porcorate Potamocherus
If you want to check out your memory usage, you should chek out Jconsole (should be in your jdk's bin). I just finished doing some work with it, and using a heap analyzer (MAT for Eclipse) to figure out why our software was running out of memory.

JulianD
Dec 4, 2005
Gah, now I have a problem entirely separate from the programming. I stupidly left Dr. Java running when I hibernated my computer, and now I'm getting the error, "Could not create the Java Virtual Machine". I've completely uninstalled and then reinstalled all of my Java applications, but the error still occurs each time I try to open Dr. Java to continue working on my programs. The best suggestion I've found so far is to reinstall my OS completely (which seems like a pretty lovely suggestion, honestly). Any better ideas out there?

hexadecimal
Nov 23, 2008

by Fragmaster

JulianD posted:

Gah, now I have a problem entirely separate from the programming. I stupidly left Dr. Java running when I hibernated my computer, and now I'm getting the error, "Could not create the Java Virtual Machine". I've completely uninstalled and then reinstalled all of my Java applications, but the error still occurs each time I try to open Dr. Java to continue working on my programs. The best suggestion I've found so far is to reinstall my OS completely (which seems like a pretty lovely suggestion, honestly). Any better ideas out there?

Try to edit the options and change the path that points to your JDK install?

Or use Eclipse, JBuilder, or NetBeans :)

dancavallaro
Sep 10, 2006
My title sucks

BELL END posted:

Really common beginner error, never use == on Strings. Use .equals() :)

Edit: as in if (choice1.equals("yes") || choice1.equals("Yes"))

You can go one step further and replace this with

code:
if (choice1.equalsIgnoresCase("yes"))

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Okay so this sounds like a pretty dumb problem but I have a generic classe that is defined in a lot of places in my program, can I use a constant (or something else?) to define the generic type (it is subclassed to Numbers)? I want to be able to switch around from integers to doubles to test things out.

Strong Sauce fucked around with this message at 09:40 on Nov 30, 2008

Mill Town
Apr 17, 2006

Strong Sauce posted:

Okay so this sounds like a pretty dumb problem but I have a generic classe that is defined in a lot of places in my program, can I use a constant (or something else?) to define the generic type (it is subclassed to Numbers)? I want to be able to switch around from integers to doubles to test things out.

You want generics: http://sys.cs.rice.edu/~sethn/wordpress/?p=6

SuperGoon
Nov 13, 2003

dancavallaro posted:

You can go one step further and replace this with

code:
if (choice1.equalsIgnoresCase("yes"))


Even better is

code:
if ("yes".equalsIgnoreCase(choice1))

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Mill Town posted:

You want generics: http://sys.cs.rice.edu/~sethn/wordpress/?p=6

Eh? My problem was with generics. But anyways I figured out that you can't define a constant for the generic type.

Emo.fm
Jan 2, 2007

Strong Sauce posted:

Eh? My problem was with generics. But anyways I figured out that you can't define a constant for the generic type.

You want AspectJ. Except no one really wants AspectJ, as far as I can tell.

My question, which is less Java related and more "data structures oh god why did I take this class this semester": implementing a splay tree. How strictly is one supposed to follow the rules of splaying every time you access a node? For example, I'm writing a method to return an array representation of the node-keys from an inorder traversal of the tree. Am I supposed to splay after visiting each node :gonk:? Or do I only splay after searching expressly for a specific key?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Emo.fm posted:

You want AspectJ. Except no one really wants AspectJ, as far as I can tell.

My question, which is less Java related and more "data structures oh god why did I take this class this semester": implementing a splay tree. How strictly is one supposed to follow the rules of splaying every time you access a node? For example, I'm writing a method to return an array representation of the node-keys from an inorder traversal of the tree. Am I supposed to splay after visiting each node :gonk:? Or do I only splay after searching expressly for a specific key?

The purpose of splaying is to optimize future accesses to similar data, which isn't meaningful for full-tree operations. Your assignment might say differently, but I've implemented a fair number of splay trees, and none of them have ever modified the tree during a full-tree operation.

rjmccall fucked around with this message at 23:03 on Nov 30, 2008

Slainhobo
Jan 9, 2004

King Shit of Fuck Mountain
I'm new to java and trying to learn IO and Exceptions, but after hours I can't figure out what i'm doing wrong. This is my first time using NetBeans. I'm making a search program that opens and looks for a word in text files in a folder. For some reason I don't see a flaw in my logic, but there must be, since it stops scanning a directory and pops out an Exception. Any insight to see what i'm doing incorrectly?

code:
    int ret;
    JFileChooser jFileChooser1;
    File somePath;
//Opens JFileChooser
private void browsehandler(java.awt.event.ActionEvent evt)
{                               
    jFileChooser1 = new JFileChooser();
    jFileChooser1.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    ret = jFileChooser1.showOpenDialog(null);

    somePath = jFileChooser1.getSelectedFile();
    jLabel3.setText(somePath.getPath());

}                              
//The Search Button Handler
private void searchhandler(java.awt.event.ActionEvent evt) {                               

    if (ret == JFileChooser.APPROVE_OPTION) {
        

            jLabel4.setText("Files found:");
            jList1.clearSelection();
            ArrayList<String> arrList = new ArrayList<String>();
            File sf = jFileChooser1.getSelectedFile();
            File[] arrFiles = sf.listFiles();
            Scanner scan = null;
            for(int i = 0; i < arrFiles.length; i++)
            {
                try {
                    File finalFile = new File(jFileChooser1.getSelectedFile() + "\\" + arrFiles[i].getName());
                    scan = new Scanner(finalFile);
                    while (scan.hasNext()) {

                        if (jTextField1.getText().equalsIgnoreCase(scan.next())) {
                            arrList.add(jFileChooser1.getSelectedFile() + "\\" + arrFiles[i].getName());
                            jList1.setListData(arrList.toArray());
                        }
                    }
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(SearchView.class.getName()).log(Level.SEVERE, null, ex);
                }
                catch (Exception e) {
                    
                }
            }
    }
}                              

KyPeN
Aug 5, 2008
Maybe someone here can help me with an issue I'm having. I'm writing a blackjack game using Swing. I have a loop going through all of the players and commencing their AI turns if they aren't human. If they are human, I don't know how to block my loop until a button press occurs. I hope this makes sense. Anyone have any familiarity with this?

EDIT: I'm a loving imbecile. Note to self:

Just don't use loops at all, moron.

Love,
Me

P.S. -- There's chicken in the fridge. Help yourself.

KyPeN fucked around with this message at 01:16 on Dec 1, 2008

Mill Town
Apr 17, 2006

Slainhobo posted:

I'm new to java and trying to learn IO and Exceptions, but after hours I can't figure out what i'm doing wrong. This is my first time using NetBeans. I'm making a search program that opens and looks for a word in text files in a folder. For some reason I don't see a flaw in my logic, but there must be, since it stops scanning a directory and pops out an Exception. Any insight to see what i'm doing incorrectly?


Knowing the type of the exception, the line it occurred on, and the stack trace will go a long way to helping someone answer that question.

Or I could run that code myself, but that won't work either since it's a snippet and not the whole application. I'm certainly not going to simulate it in my head.

Clanpot Shake
Aug 10, 2006
shake shake!

I'm having some trouble using the PriorityQueue class. It's not keeping things in the order it should be, and I'm not sure why. I have a PQ of Nodes, which implements comparable:
code:
public int compareTo(Node right)
{
	if (this.getTotal() > right.getTotal())   //getTotal() returns a double
		return -1;
	if (this.getTotal() < right.getTotal())
		return 1;
	return 0;
}
I want the Nodes to be sorted in the PQ with the lowest totals first, but that's not what's happening - it's not putting them in any discernible order at all. I'm looking at the PQ in the Eclipse debugger and it seems pretty random, but I know it isn't because if I change the inequalities the order changes (but it's still wrong).

What am I doing wrong here?

edit: I figured out what order it's putting them in - the order in which they were created. Eclipse labels each object you create and gives it an ID number and apparently the PQ is sorting by this.

double edit!: As I said, I'm using Eclipse, and it's doing something strange. I'm getting different output depending on if I run it or debug (run with breakpoints) it. Both methods are running in the same place with the same arguments, but they spit out different stuff. Who ever heard of such a thing.

Clanpot Shake fucked around with this message at 03:43 on Dec 1, 2008

Idran
Jan 13, 2005
Grimey Drawer

SuperGoon posted:

Even better is

code:
if ("yes".equalsIgnoreCase(choice1))

I must be missing something, why is this better? Isn't this equivalent to the other method?

SuperGoon
Nov 13, 2003

Idran posted:

I must be missing something, why is this better? Isn't this equivalent to the other method?

What happens when choice1 is null in the original example?

That convention does a null check and an .equals type check all in one.

Idran
Jan 13, 2005
Grimey Drawer

SuperGoon posted:

What happens when choice1 is null in the original example?

That convention does a null check and an .equals type check all in one.

Oh, you're right, I didn't even think about that. I always forget to check for null until it ends up biting me down the line, so that didn't even occur to me. Cool, I'll have to remember that convention, then.

Outlaw Programmer
Jan 1, 2008
Will Code For Food

Clanpot Shake posted:

Problems with PriorityQueue...

According to the docs, it looks like you need to pass a Comparator in the constructor of the PriorityQueue; It's not enough to just have your elements implement Comparable.

I think the whole thing might boil down to:

code:
PriorityQueue<Node> queue = new PriorityQueue<Node>(new Comparator<Node>()
{
    public int compare(Node n1, Node n2)
    {
        return n2.getTotal() - n1.getTotal();
    }
});

Outlaw Programmer fucked around with this message at 07:58 on Dec 1, 2008

Clanpot Shake
Aug 10, 2006
shake shake!

Outlaw Programmer posted:

I think the whole thing might boil down to:
That seems to have helped, but it doesn't look like the PQ is maintaining the order of its elements as I go through them. I'm not using an iterator, I'm using the poll() method.

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost

Idran posted:

Oh, you're right, I didn't even think about that. I always forget to check for null until it ends up biting me down the line, so that didn't even occur to me. Cool, I'll have to remember that convention, then.
And while you're at it, don't go do the if (null == possiblyNullObject) check religiously (instead of if (possiblyNullObject == null) ) like people do in C/C++ when you're doing Java - that convention has to do with C/C++'s lack of type constraints upon conditional expressions, which is enforced in Java (and C#) to be booleans. Some of my coworkers do that and it drives me nuts because then I go into C++ mode and I start having language shock and start wondering where all the free(ptr) and delete(ptr) calls went.

Clanpot Shake
Aug 10, 2006
shake shake!

More PriorityQueue nonsense:

This is the Node comparator used by my PQ:
code:
public int compare(Node a, Node b) 
{ 
	int aVal = (int)(a.getTotal() * 100000); 
	int bVal = (int)(b.getTotal() * 100000);
        if (bVal > aVal)
            return -1;
        else if (bVal < aVal)
            return 1;
        else
            return 0;
}
The comparator must return an int, and because some of my nodes are close together I need to scale their total to minimize integer approximation errors.

Anyway, The queue isn't popping off items in the correct order. For the life of me, I can't figure out what order it IS popping them off in. It's not the highest or lowest total, that's for sure. Is there a way to force the queue to reorder itself, or is it decided what item to pop off when poll() is called?

Is it okay to dynamically add and remove items from a PQ and have it maintain order?

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I have a question about WizardPage's with jface, but I think it might be more general to dialogs in Eclipse SWT. I am finding if I try to change graphical elements in the WizardPage, they don't get updated. So let's say I have a button that I click and a listener attached. I can see the listener is running through debug print statements. I try to setText() on the button, yet I don't see the button reflect to change the new text.

I assume redraw events aren't making it back properly, but I don't know how to link it all up. redraw() commands from the handler aren't doing the job. Any ideas?

Edit: Figured it out. Holy poo poo. You have to spin off Runnables that ask the shell to redraw. I guess some of that has to do with the wizard page being in a dialog, so the message handling is all internal.

Rocko Bonaparte fucked around with this message at 19:30 on Dec 2, 2008

the onion wizard
Apr 14, 2004

Clanpot Shake posted:

Is there a way to force the queue to reorder itself, or is it decided what item to pop off when poll() is called?
poll() will always return the head, I don't believe you can (or need to) force a sort.

Clanpot Shake posted:

Is it okay to dynamically add and remove items from a PQ and have it maintain order?
Provided only one thread at a time accesses the queue, yes.


It might be time to post more code...

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Outlaw Programmer posted:

According to the docs, it looks like you need to pass a Comparator in the constructor of the PriorityQueue; It's not enough to just have your elements implement Comparable.

This is incorrect; if you fail to provide a comparator, it will fall back on the natural ordering, which assumes that the objects implement Comparable.

Clanpot, is it too much to ask to post the fulltext of Node as well as your insertion/removal code? I think you must be making some very silly mechanical error.

Outlaw Programmer posted:

code:
PriorityQueue<Node> queue = new PriorityQueue<Node>(new Comparator<Node>()
{
    public int compare(Node n1, Node n2)
    {
        return n2.getTotal() - n1.getTotal();
    }
});

This is probably correct here, but I'm under contract with the PL Pedant's Union to observe that this relies on particular assumptions about the range of getTotal() and that people shouldn't get in the habit of using this shortcut without thinking about it.

Brain Candy
May 18, 2006

Clanpot Shake posted:

...

code:
int aVal = (int)(a.getTotal() * 100000); 
int bVal = (int)(b.getTotal() * 100000);
The comparator must return an int, and because some of my nodes are close together I need to scale their total to minimize integer approximation errors.

Are you sure this does what you think it does? i.e. (int) (6.99999997 * 10) = 69 but (int) (7.0000001 * 10 ) = 70. For positive numbers, (int) is equivalent to floor, not the nearest integer.

Clanpot Shake
Aug 10, 2006
shake shake!

Brain Candy posted:

Are you sure this does what you think it does? i.e. (int) (6.99999997 * 10) = 69 but (int) (7.0000001 * 10 ) = 70. For positive numbers, (int) is equivalent to floor, not the nearest integer.
I know what it's doing, and for my purposes sliding the decimal point half a dozen places over and chopping it off is close enough.

Right then, here's my Node code:
code:
package homework;

import java.util.*;

public class Node implements Comparable<Node>
{
	public HashMap<Node, Double> neighbors;
	public Node previous;
	public String name;
	public DPoint location;
	// cost = actual distance from start to this in a straight line
	// heuristic = distance from this to goal in a straight line
	double cost, heuristic, total;
	
	public Node(String n)
	{
		name = n;
		location = new DPoint();
		neighbors = new HashMap<Node, Double>();
	}
	public Node(Node n)
	{
		name = n.getName();
		location = n.getLocation();
		neighbors = new HashMap<Node, Double>(n.getNeighbors());
	}
	public Node(String n, double x, double y)
	{
		name = n;
		location = new DPoint(x,y);
		neighbors = new HashMap<Node, Double>();
	}
	public Node(String n, DPoint a)
	{
		name = n;
		location = a;
		neighbors = new HashMap<Node, Double>();
	}
	public void addNeighbor(Node n, double distance)
	{
		neighbors.put(n, distance);
	}
	public void setNeighbors(HashMap<Node, Double> n)	{	neighbors = n;	}
	public String getName() 				{ 	return name;		}
	public HashMap<Node, Double> getNeighbors()		{	return neighbors;	}
	public DPoint getLocation()				{	return location;	}
	public double getCost()					{ 	return cost;		}
	public double getHeuristic()				{	return heuristic;	}
	public void setPrevious(Node n)				{	previous = n;		}
	public Node getPrevious()				{	return previous;	}
	public double getTotal()							
	{
		total = cost + heuristic;
		return total;			
	}
	
	public void setCost(double c)			{	cost = c;	}
	public void setCost(String c)			
	{		
		for (Node n : neighbors.keySet())
			if (n.name == c)
				cost = neighbors.get(n);
	}
	public void addCost(double c) 			{ 	cost += c;			}
	public void setHeuristic(double h)		{	heuristic = h;			}
	public void setTotal(double t)			{	total = t;			}
	
	public void calcCost(Node start)
	{	cost = location.distance(start.getLocation());		}	
	public void calcHeuristic(Node goal)
	{	heuristic = location.distance(goal.getLocation());	}	
	
	public String toString()
	{
		String s = "";
		for (Node n : neighbors.keySet())
			if (n != null)
				s = s + n.getName() + " ";
		return name;// + " at ("+location.getX()+","+location.getY()+") is connected to " + s;
	}
	public String verbose()
	{
		String s = "";
		for (Node n : neighbors.keySet())
			if (n != null)
				s = s + n.getName() + "("+ neighbors.get(n).doubleValue()+") ";
		return name + " at ("+location.getX()+","+location.getY()+") is connected to " + s;
	}
	
	public boolean equals(Object right)
	{
		if (this.name == ((Node)right).name)
			return true;
		if (!(right instanceof Node))
			return false;
		return (this.getLocation().equals(((Node)right).getLocation()));
	}
	
	public int compareTo(Node right)
	{
		if (this.getTotal() > right.getTotal())
			return -1;
		if (this.getTotal() < right.getTotal())
			return 1;
		return 0;
	}
	public static double distanceBetween(Node x, Node y)
	{
		double Lat1, Lat2, Long1, Long2;
		Lat1 = x.getLocation().getX();
		Lat2 = y.getLocation().getX();
		Long1 = x.getLocation().getY();
		Long2 = y.getLocation().getY();
		return 3963.0 * (2 * Math.asin(
				Math.sqrt(Math.pow(Math.sin(
						Math.toRadians((Lat2-Lat1)/2)),2) + 
						Math.cos(Math.toRadians(Lat1)) *
						Math.cos(Math.toRadians(Lat2)) *
						Math.pow(Math.sin(Math.toRadians((Long2-Long1)/2)), 2))));				
	}
}
I know, it's full of bloat. Here's my insertion code:
code:
PriorityQueue<Node> open = new PriorityQueue<Node>(10,new Comparator<Node>() 
{ 
// orders the nodes in ascending order by total score
	public int compare(Node n1, Node n2) 
	{ 
		int aVal = (int)((n1.getCost() + n1.getHeuristic()) * 100000);
		int bVal = (int)((n2.getCost() + n2.getHeuristic()) * 100000);

                    if (bVal > aVal)
                            return -1;
                    else if (bVal < aVal)
                            return 1;
                    else
                            return 0;
	} 
});		
PriorityQueue<Node> closed = new PriorityQueue<Node>(/*same as above*/);	
ArrayList<Node> path = new ArrayList<Node>();
		
start.setCost(0);		
open.add(start);		
		
double tentscore;				// the cost of the path currently being explored
boolean tent_is_better;			// true means the path we're looking at is better
while (!open.isEmpty())
{
	//Arrays.sort(open.toArray());
	//current = open.remove();	
			
	current = open.poll();
	if (current.equals(goal))		//PATH COMPLETE, reconstruct the path
	{
		System.out.print("On node " + current.getName()+"\n");
		path = reconstructPath(current);
		break;
	}
	else
	{
		System.out.print("On node " + current.getName()+", exploring neighbors...\n");
		closed.add(current);
		for (Node n : current.getNeighbors().keySet())
		{
			System.out.print("\tExploring node " + n.getName()+"...");
			if (closed.contains(n))
			{	
				System.out.print(" Already explored, moving on.\n");
				continue;
			}
			tentscore = current.getCost() + Node.distanceBetween(n, current);
			tent_is_better = false;
			if (!open.contains(n))
			{
				System.out.print(" Adding "+n.getName()+" to the open set, ");
				[b]//open.offer(n);[/b]
				n.setHeuristic(Node.distanceBetween(n, goal));
				tent_is_better = true;
			}
			else if (tentscore < n.getCost())
				tent_is_better = true;
			if (tent_is_better)
			{
				//System.out.print("Adding " + n.getName() + " to the path \n");
				n.setPrevious(current);
				n.setCost(current.name);
				n.addCost(current.getCost());
				n.setTotal(n.getCost() + n.getHeuristic());
				//[b]open.offer(n);[/b]  // UNCOMMENT THIS
				System.out.printf("\n\t\tCost of node: %.2f miles\n\t\tHeuristic Value:
			 %.2f miles\n\t\tEstimated Total Cost of node: %.2f miles\n",
			tentscore,n.getHeuristic(),n.getTotal());
			}
			System.out.print("\tFinished with node " + n.getName()+"\n");
		}
		System.out.print("Finished with node " + current.getName()+"\n");
	}
}	// END WHILE
reportFindings(path);
If you don't recognize it, this is the A* search algorithm. Everything but the PQ seems to be working fine.

edit: I think I fixed it. The problem was that I was adding Nodes to the PQ before modifying them, which threw off the priority order (even though the nodes in the queue themselves were modified). I've bolded the offending lines. Apparently code blocks don't take formatting. Oh well.

Clanpot Shake fucked around with this message at 20:30 on Dec 2, 2008

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Clanpot Shake posted:

edit: I think I fixed it. The problem was that I was adding Nodes to the PQ before modifying them, which threw off the priority order (even though the nodes in the queue themselves were modified).

Yes, that's definitely the problem; you're breaking the data structure's invariants. I should have considered that before asking you to post your code.

Just some general notes:
  • The way you use setCost(String) during neighbor-update is ridiculous: you already have a handle on the source node (current), you've even set it as previous on the node, but in order to derive the cost to the source node you... linearly search the target node's in-edges for a node with that name?
  • Why is closed a priority queue? The only operation you perform on it is membership testing; a set would be much faster, but in this case you could get away with a flag on the node.
  • Queues where you frequently modify the priority of elements already in the queue aren't really ideal for over-the-counter data structures. It'd be much more efficient to use an invasive heap, especially since you know that priorities only ever drop.
  • With a lot of distance-based algorithms, it's better to work with squared distances; that might be problematic here, because of course you can't add them correctly. But it would eliminate a lot of possibly unnecessary square-roots.

Clanpot Shake
Aug 10, 2006
shake shake!

rjmccall posted:

Just some general notes:
The way you use setCost(String) during neighbor-update is ridiculous: you already have a handle on the source node (current), you've even set it as previous on the node, but in order to derive the cost to the source node you... linearly search the target node's in-edges for a node with that name?
That was a last-minute hack to fix an earlier bug. These things tend to happen when I don't think things through all the way. I have a habit of doing that.

rjmccall posted:

Why is closed a priority queue? The only operation you perform on it is membership testing; a set would be much faster, but in this case you could get away with a flag on the node.
I noticed this after I posted. I've since changed it to something more appropriate, but a collection makes it easier for debugging purposes.

The other two things are good points, but I don't have any specific response to them. There is one thing you missed though (I did too, and I'm still working on it).

Node implements equals, but not hashCode, which it's supposed to. Because it doesn't, closed.contains(n) (contains calls equals()) won't function properly, and some nodes will be explored more than once. As I said, I'm still working on fixing this.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Clanpot Shake posted:

Node implements equals, but not hashCode, which it's supposed to. Because it doesn't, closed.contains(n) (contains calls equals()) won't function properly, and some nodes will be explored more than once. As I said, I'm still working on fixing this.

Actually, I would guess that your equals and hashCode methods are already de facto consistent; the requirement is just that A.equals(B) implies (A.hashCode()==B.hashCode()), and I bet you never have two distinct nodes that are actually equal (i.e. have the same position). In fact, it looks like you'd probably have bugs if you did— priority queues certainly don't enforce set semantics on insertion. I would strongly suggest dropping back to reference-equality semanics, since distinct nodes are really distinct entities anyway.

smada
Jan 3, 2007
I'm trying to manipulate one of my pages to see if it catches auto voting, and I'm wondering how to go about doing this. Basically the page (javascript) has a few radio buttons with options selected, and a final radio with a blank text box for optional input. Should I write a script with Ajax to use the get/post and see If it'll accept it, or is there an easier way?

Code posted:

<form name="voteForm" action="thanksVote" method="POST">
<table width="560px" border="0">
<colgroup>
<col width="10px" nowrap>

<col width="240px" nowrap>

<col width="50px" nowrap>
<col width="10px" nowrap>
<col width="250px" nowrap>
</colgroup>
<tr>
<td><input name="vote" type="radio" value="41"></td>
<td><a href="http://gainesvillegreen.net/option1" target="_blank">blah1</a>
</td><td><input type="radio" name="vote" value="42"></td>
<td><a href="gainesvillegreen.net/option2" target="_blank">blah2</a>
<tr>
<td><input name="vote" type="radio" value="custompick"></td>
<td><input type="text" style="width:200px;" name="custompick" id="custompick" maxlength="40"></td>
</tr>
</table>
<div id="vote"><input type="image" src="http://gainesvillegreen.net/images/vote_now.jpg"></div>

</form>

Mill Town
Apr 17, 2006

basic360 posted:

I'm trying to manipulate one of my pages to see if it catches auto voting, and I'm wondering how to go about doing this. Basically the page (javascript) has a few radio buttons with options selected, and a final radio with a blank text box for optional input. Should I write a script with Ajax to use the get/post and see If it'll accept it, or is there an easier way?

Java is not JavaScript. Try here:
http://forums.somethingawful.com/showthread.php?threadid=2718078

zokie
Feb 13, 2006

Out of many, Sweden
This is probably a stupid question but my teacher sucks, so here goes:

code:
public class Frog {
    
    private int variable;

    public int getVariable() {
        return variable;
    }
    
    public void setVariable(int variable) {
        this.variable = variable;
    }

    public void add(int amount) {
        setVariable(getVariable() + amount);
    }
}
(Some stuff obviously omitted)

The book we have been using, and how I would do the add method is like this:

code:
    public void add(int amount) {
        variable += amount;
    }
And I can't for the love of all that is unholy understand why you would want to use the get and set methods while still in the class.
Is this some kind of industry standard and I should be doing it like that, if so why?

hexadecimal
Nov 23, 2008

by Fragmaster

zokie posted:

This is probably a stupid question but my teacher sucks, so here goes:

code:
public class Frog {
    
    private int variable;

    public int getVariable() {
        return variable;
    }
    
    public void setVariable(int variable) {
        this.variable = variable;
    }

    public void add(int amount) {
        setVariable(getVariable() + amount);
    }
}
(Some stuff obviously omitted)

The book we have been using, and how I would do the add method is like this:

code:
    public void add(int amount) {
        variable += amount;
    }
And I can't for the love of all that is unholy understand why you would want to use the get and set methods while still in the class.
Is this some kind of industry standard and I should be doing it like that, if so why?

You don't have to use modifiers and accessors, but for a more complicated data structure those make a lot more sense to use inside the class even if you have access to actual private/protected variables inside the class. The reason is, is that add or get commands could be a lot more complex than one line. Using them from inside your own class just saves on code duplication.

Also it makes your code more readable to the user trying to understand implementation of your class.

csammis
Aug 26, 2003

Mental Institution

zokie posted:

And I can't for the love of all that is unholy understand why you would want to use the get and set methods while still in the class.

What if your set method did this:

code:
public void setVariable(int variable)
{
  int oldValue = this.variable;
  this.variable = variable;

  // Alert registered listeners that the value of variable has changed
  for(IVariableChangedListener listener : variableChangedListeners)
  {
    listener.variableChanged(oldValue, variable);
  }
}
If you did what you suggest and accessed variable directly, the change listeners would never get notified, or you'd have to invoke the change listeners everywhere you set variable.

zokie
Feb 13, 2006

Out of many, Sweden
Thanks hexadecimal and csammis, I get it now :v:

Adbot
ADBOT LOVES YOU

Boz0r
Sep 7, 2006
The Rocketship in action.
I'm doing a Java Applet for programming class, and my applet works fine in eclipse, but as soon as I load it into a html file, it doesn't.

code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SceneEditor extends JApplet
{
   public void init()
   {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      final SceneComponent scene = new SceneComponent();

      JButton houseButton = new JButton("House");
      houseButton.addActionListener(new
         ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               scene.add(new HouseShape(20, 20, 50));
            }
         });

      JButton carButton = new JButton("Car");
      carButton.addActionListener(new
         ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               scene.add(new CarShape(20, 20, 50));
            }
         });

      JButton removeButton = new JButton("Remove");
      removeButton.addActionListener(new
         ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               scene.removeSelected();
            }
         });

      JPanel buttons = new JPanel();
      buttons.add(houseButton);
      buttons.add(carButton);
      buttons.add(removeButton);

      frame.add(scene, BorderLayout.CENTER);
      frame.add(buttons, BorderLayout.NORTH);

      frame.setSize(300, 300);
      frame.setVisible(true);
   }
}
The problem is from the Horstmann book Design & Patterns. Their website has the solutions online, but theirs doesn't work either.

http://www.horstmann.com/oodp2/solutions/Ch8/Ex3/index.html

What could be wrong?

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