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
Jehde
Apr 21, 2010

I'm creating a simple game, main algorithm for the game is in a main method along with this additional method on how to choose the player difficulty:

code:
    private void createPlayerOne(int difficulty, int startx, int starty, int tactic)
    {
    	if (difficulty == 1)
    	{
    		Easy player = new Easy(startx, starty);
    	}
    	else if (difficulty == 2)
    	{
    		Medium player = new Medium(startx, starty);
    	}
    	else if (difficulty == 3)
    	{
    		Hard player = new Hard(startx, starty);
    	}
    	else
    	{
    		Expert player = new Expert(startx, starty, tactic);
    	}
    }
But ofcourse these are initialized out of scope, is there any way to get around this?

Adbot
ADBOT LOVES YOU

Paolomania
Apr 26, 2006

What language are you coming from? It is fairly clear that you are not "thinking in Java".

epswing
Nov 4, 2003

Soiled Meat
You probably want something more like...
code:
    
abstract class Player { ... }
class EasyPlayer extends Player { ... }
class MediumPlayer extends Player { ... }
class HardPlayer extends Player { ... }
class ExpertPlayer extends Player { ... }

private Player createPlayer(int difficulty, int startx, int starty, int tactic)
{
    Player player;
    
    switch (difficulty) {
        case 1:
            player = new EasyPlayer(startx, starty);
            break;
        case 2:
            player = new MediumPlayer(startx, starty);
            break;
        case 3:
            player = new HardPlayer(startx, starty);
            break;
        default:
            player = new ExpertPlayer(startx, starty, tactic);
    
    return player;
}
E: The idea that you can do Player p = new EasyPlayer() is called polymorphism.

epswing fucked around with this message at 16:07 on Dec 6, 2010

Dub Step Dad
Dec 29, 2008
Recently I've begun taking classes at my university in Java, which is my first language, so I have a question that's probably pretty simple.
We just started covering MVC architecture, and in a project we're doing I have to create a class "Tile" that extends JButton, and then in my GUI create a 9x9 2D array of Tile objects to be displayed as a big square of buttons, and then using a set of radio buttons and a combo box I can set the background and the foreground of the tiles. Holding the Color information of the tiles I have another array of a class, TileInfo.
My problem is that my Tile class is my view, the main GUI class is the controller, and the TileInfo is the model, but when my ActionListener for the tiles is called, I don't know how I can make my program differentiate between different objects in the Array without creating 81 if statements, and then after that be able to reference the TileInfo object that corresponds to the Tile.

tef
May 30, 2004

-> some l-system crap ->

epswing posted:

You probably want something more like...

An enum for difficulty, stored as an attribute somewhere it makes sense.

epswing
Nov 4, 2003

Soiled Meat
His program might depend on the implementation of each player class...

:negative:

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa

epswing posted:

His program might depend on the implementation of each player class...

:negative:

...so it should be encapsulated inside the player class itself to avoid doing extra conditionals in various places.

Well OK, "player" as a class concept for difficulty most likely isn't the correct place for that code but anyways.

epswing
Nov 4, 2003

Soiled Meat
I don't presume to know how you're building your program. I'm just showing you a way to create and return a new Player, because your original problem was scope.

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Puppet Pal Claudius posted:

Recently I've begun taking classes at my university in Java, which is my first language, so I have a question that's probably pretty simple.
We just started covering MVC architecture, and in a project we're doing I have to create a class "Tile" that extends JButton, and then in my GUI create a 9x9 2D array of Tile objects to be displayed as a big square of buttons, and then using a set of radio buttons and a combo box I can set the background and the foreground of the tiles. Holding the Color information of the tiles I have another array of a class, TileInfo.
My problem is that my Tile class is my view, the main GUI class is the controller, and the TileInfo is the model, but when my ActionListener for the tiles is called, I don't know how I can make my program differentiate between different objects in the Array without creating 81 if statements, and then after that be able to reference the TileInfo object that corresponds to the Tile.
It's hard to say without seeing the code in more detail, but it sounds like you want to do something like storing the x coordinate and y coordinate of the tiles (or some other unique identifier) in both the Tile and TileInfo objects, which will allow you to check which corresponds to which. The most straightforward thing would be for Tile to have a direct reference to TileInfo, but I'm not sure if that would make sense in your specific case.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
I have created an SSL socket server, I think correctly using code similar to:
code:
SSLServerSocketFactory ssocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
server = ssocketFactory.createServerSocket(port);
where server is an SocketServer and port == 443

I have created a certificate using:

keytool -genkey -keystore mySrvKeystore -keyalg RSA

I have code else where that starts a listener and accepts when a connection is made.

I started up the java server with the additional vm params:

-Djavax.net.ssl.keyStore=<the store filename> -Djavax.net.ssl.keyStorePassword=<the password>

I created a quick java client to connect (and have also used openssl for testing). I see on the server side the connection made, but the client:

1. Cannot retrieve the certificate for viewing
2. Writes data on the socket, but nothing appears on the server side

What am I missing?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
You need to use the certificate you created in your client and add it to the truststore for the SSLConnectionFactory or whatever it's called before trying to connect to the server. Or you can disable the check for the server's certificate but that's not a good idea in the real world.

Oh also make sure that your certificate includes your hostname in the common name field.

DholmbladRU
May 4, 2006
I am trying to create a server and client java classes that communicate through socket. I can create a connection, however when I attempt to pass data I get a null pointer.

I can successfully connect, however I am having some problems passing messages back and fourth.

code:
try{
					message = (String)in.readObject();
					System.out.println("Enter either add or mult and two integers");
					s = new Scanner(System.in);
					while(s.nextLine() != null){
						String temp = s.nextLine();
						sendMessage(temp);


						
					}
				}
And here is where I am receiving the message.

code:
	try{
					message = (String)in.readObject();
					s = new Scanner(message);
					System.out.println(message);
					String operator = s.next();
					System.out.println(operator);
					int numA = Integer.parseInt(s.next());
					System.out.println(numA);
					int numB = Integer.parseInt(s.next());
					System.out.println(numB);
					int tempInt = 0;
					if (operator.equals("add") && operator != null)
						
						tempInt = numA+numB;
						sendMessage(tempInt+"");
				}
Haven't programed java that much, so im probably breaking a number of rules.

epswing
Nov 4, 2003

Soiled Meat
Where (which line) does the NPE occur?

You're not showing us enough code. Show us the sendMessage method, and the rest of the body of your receiveMessage method.

DholmbladRU
May 4, 2006
send method was taken from the fallowing, http://zerioh.tripod.com/ressources/sockets.html

This seems to be doing what I need it to on the client side.
code:
try{
					message = (String)in.readObject();
					System.out.println("Enter either add or mult and two integers");
					s = new Scanner(System.in);
					while(s.hasNext() || message !=null){
						String temp = s.nextLine();
						sendMessage(temp);
					
					}
				}
code:
message = (String)in.readObject();
					s = new Scanner(message);
					System.out.println(message);
					String operator = s.next();
					int numA = Integer.parseInt(s.next());
					int numB = Integer.parseInt(s.next());
					
					int tempInt = 0;
					if (operator.equals("add") && operator != null){
						tempInt = numA+numB;
						System.out.println("server>" + tempInt);
						sendMessage(tempInt+"");
						
					}if(operator.equals("mult") && operator != null){
						tempInt = numA*numB;
						System.out.println("server>" + tempInt);
					}
This all works properly, however the wrong class is sending out the answer. I need the answer of 'add 10 10' to be output to the clients console. At the moment it is output by the servers console in this line
'System.out.println("server>" + tempInt);'

DholmbladRU fucked around with this message at 22:49 on Dec 7, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Instead of:

while(s.nextLine() != null)

don't you want:

while (s.hasNextLine())

DholmbladRU
May 4, 2006
thanks got that all figured out. havnt programed any java in awhile.

Trick Question
Apr 9, 2007


I am trying to use a priority queue to hold objects for a game I and some others are creating, as such:
code:

...
public Hand()
	{
		Comparator<Card> comparator1 = new CardComparator();
		ourHand = new PriorityQueue<Card>(108, comparator1);
	}
	
	public class CardComparator implements Comparator<Card>
	{
		public CardComparator(){
			super();
		}
		
		public int compare(Card c, Card d)
		{
			if(c.getSuit() > d.getSuit()) return 1;
			if(c.getSuit() < d.getSuit()) return -1;
			if(c.getValue() < d.getValue()) return -1;
			if(c.getValue() > d.getValue()) return 1;
			else return 0;
		}
	}
...
The problem is, I can't remove anything from this queue, and it doesn't actually sort the contained objects in any way, shape, or form. So, what am I loving up?

Surface
May 5, 2007
<3 boomstick

Trick Question posted:

I am trying to use a priority queue to hold objects for a game I and some others are creating...

Doesn't look like the problem is here, what method are you using to remove something
code:
ourHand.remove(aCardObject)
should work... I can't see a reason it wouldn't work unless you are doing something like:

code:
Card spades5 = new Card(Spades,5);
Card anotherSpades5 = new Card(Spades,5);
ourHand.add(spades5);
ourHand.remove(anotherSpades5); //wont do anything
This wont work because even though both cards are 5 of spades, they are two different instances, and PriorityQueue tests for object equality via object.equals(object2);

If you override the .equals() and .hashCode() method of your card class the above code will work, but instead consider only instantiating one card object per card.

As for the sorting, does this line of the PriorityQueue javadocs apply to you:

JavaDocs posted:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

Surface fucked around with this message at 21:28 on Dec 9, 2010

brosmike
Jun 26, 2009
To clarify, if you mean you want to remove the highest-priority item in the queue, the method you're looking for is poll, not remove.

epswing
Nov 4, 2003

Soiled Meat
Surface alluded to this, but I'll make it clear.

When using collection-like classes (List, Set, Map, Queue, etc) writing anything non-trivial, you really should properly implement .equals() and .hashCode() methods for the objects you want to reference, otherwise Java won't really understand how to compare anything, and you'll end up with undefined behavior that'll make you want to set yourself on fire.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Epswing is totally on the money here. And whatever you do, don't just overload .equals() and leave .hashCode() as the default implementation- it'll violate the .equals() contract and gently caress things up in hilariously subtle ways.

Paolomania
Apr 26, 2006

especially if you are fond of using HashMap and HashSet

Surface
May 5, 2007
<3 boomstick

Internet Janitor posted:

Epswing is totally on the money here. And whatever you do, don't just overload .equals() and leave .hashCode() as the default implementation- it'll violate the .equals() contract and gently caress things up in hilariously subtle ways.

Haha yes I should edit this into my post.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"
What's really fun is teaching students in a second-semester Java data structures class the proper way to implement equals and hashCode, especially when the concept of hash tables hasn't been introduced yet so a hash code seems pointless to them. (Why teach hashCode without mentioning hash tables? If we're teaching them to override equals, it's better that we mention hashCode at the same time since the two are so closely related.)

I saw so much of this last semester:

code:
public boolean equals(Object other)
{
    return hashCode() == other.hashCode();
}
:(

Some students at least understood that you could use the hashcodes to short-circuit for inequality but that it doesn't say anything about equality, but even that makes my skin crawl a little bit for some reason.

Fly
Nov 3, 2002

moral compass

Flobbster posted:

code:
public boolean equals(Object other)
{
    return hashCode() == other.hashCode();
}
Please teach them. I've been seeing this in job candidates, too. :ughh:

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Flobbster posted:

What's really fun is teaching students in a second-semester Java data structures class the proper way to implement equals and hashCode, especially when the concept of hash tables hasn't been introduced yet so a hash code seems pointless to them. (Why teach hashCode without mentioning hash tables? If we're teaching them to override equals, it's better that we mention hashCode at the same time since the two are so closely related.)

I saw so much of this last semester:

code:
public boolean equals(Object other)
{
    return hashCode() == other.hashCode();
}
:(

Some students at least understood that you could use the hashcodes to short-circuit for inequality but that it doesn't say anything about equality, but even that makes my skin crawl a little bit for some reason.

I always thought the contract for hashCode was that it had to match the same things that equals did, but after reading the spec that's not the case. God drat that's a terrible way to introduce subtle bugs.

That code is still inexcusable, they should at least check for nulls and that's its the same type!

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

MEAT TREAT posted:

I always thought the contract for hashCode was that it had to match the same things that equals did, but after reading the spec that's not the case. God drat that's a terrible way to introduce subtle bugs.

That code is still inexcusable, they should at least check for nulls and that's its the same type!

Whoops missed an important word! nvm this

Trick Question
Apr 9, 2007


Thanks for all the help. After adding
code:
public boolean equals(Object card2){
	   if(card2 instanceof Card){
		   if(value == ((Card) card2).getValue() && suit == ((Card) card2).getSuit()){
			   return true;
		   }
		   return false;
	   }
	   else return false;
   }
   
   public int hashCode(){
	   int suitOffset = 15*suit;
	   int returnCode = suitOffset + value;
	   return returnCode;
   }
The remove works just fine, and our game is basically working. Still, it ain't quite sorting as I'd like it to. Anyone have any idea why this is?

Necc0
Jun 30, 2005

by exmarx
Broken Cake
for the life of me I can't figure out how graphics2D is supposed to work. the two relevant classes:

http://pastebin.com/vMsCXtcC

and:

http://pastebin.com/PjzNe2hD

I've tried setting jPanel1 equal to the draw object, then running the draw object. I've tried passing display.jPanel1 into the drawImage functions, and now I've tried the current iteration. No matter what I do I get nothing to the screen.

I know the images are in the right place because the older iteration of this program was just using the graphics library to draw, and while it worked it looked terrible and took forever to refresh.

edit: sorry about all the commented out lines I've been throwing poo poo at this for a few hours now and I know it's something really minor and easy

edit2: not nearly as annoying now

Necc0 fucked around with this message at 05:12 on Dec 10, 2010

RitualConfuser
Apr 22, 2008

Trick Question posted:

The remove works just fine, and our game is basically working. Still, it ain't quite sorting as I'd like it to. Anyone have any idea why this is?
In what way is it not sorting correctly?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Necc0 posted:

for the life of me I can't figure out how graphics2D is supposed to work. the two relevant classes:

Might wanna use something like http://www.pastebin.com/ instead of posting a ton of code in the thread.

Trick Question
Apr 9, 2007


RitualConfuser posted:

In what way is it not sorting correctly?

Preferably, I'd have it sorting by suit then value. However, right now, it doesn't appear to be sorting at all, as such:
code:
[1 of Red, 2 of Red, 2 of Blue, wild draw four of Black, 7 of Red, 2 of Green, 2 of Yellow]
I'd assumed making a comparator for it like
code:
private PriorityQueue<Card> ourHand;
private Comparator<Card> comparator1;
...
public Hand()
	{
		comparator1 = new CardComparator();
		ourHand = new PriorityQueue<Card>(108, comparator1);
	}

...
public class CardComparator implements Comparator<Card>
	{
		public CardComparator(){
			
		}
		
		public int compare(Card c, Card d)
		{
			if(c.getSuit() > d.getSuit()) return 1;
			if(c.getSuit() < d.getSuit()) return -1;
			if(c.getValue() < d.getValue()) return -1;
			if(c.getValue() > d.getValue()) return 1;
			else return 0;
		}
	}
would cause it to sort like that, but it doesn't seem to have worked. Any advice?

RitualConfuser
Apr 22, 2008
I made a simple implementation of Card with suit and value as int's and it sorts fine for me using that Comparator. What does the implementation of Card look like?

Necc0
Jun 30, 2005

by exmarx
Broken Cake

fletcher posted:

Might wanna use something like http://www.pastebin.com/ instead of posting a ton of code in the thread.

thanks a bunch

Trick Question
Apr 9, 2007


RitualConfuser posted:

I made a simple implementation of Card with suit and value as int's and it sorts fine for me using that Comparator. What does the implementation of Card look like?

Like this.

be forewarned, I probably haven't commented that as well as I should have.

RitualConfuser
Apr 22, 2008
OK, the issue is in the comparator. Basically, you need a simple way to generate a unique number for each suit/value combo such that it maintains ordering (hint: it's already somewhere in your code). Then in the comparator, you can return the difference of the 2 card's unique numbers. So, if you had a deck of 52 cards, how would you order them such that the cards are assigned a unique number between 0 and 51? Does that make sense? You could also use something other than a PriorityQueue but that might require more changes in your code.

E: I probably should have tested that out first... I think what you might be looking for is a SortedSet instead of a PriorityQueue. That assumes that you can't have more than one card of the same suit/value though, which may not be what you want.

RitualConfuser fucked around with this message at 07:13 on Dec 10, 2010

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
RC: what you even I don't know

TQ, neither Card and CardComparator is the source of your bugs. You problem is that you have code that looks something like this:

code:
for (Card c : ourHand) { ... }
This is wrong because PriorityQueue does not guarantee that it will keep the entire queue sorted at all times; it guarantees only that, at any given point, the element returned by peek() and poll() will not be greater than anything left in the queue.

I know you are doing this, or something equivalent, because these elements are actually in heap order, where the element at index N is smaller than the elements at index 2(N+1)-1 and 2(N+1). That is because PriorityQueue is internally implemented using the "heap" data structure.

What you should be doing instead is something like:
code:
while (!ourHand.empty()) { Card c = ourHand.poll(); ... }

RitualConfuser
Apr 22, 2008

rjmccall posted:

RC: what you even I don't know
For some reason I was thinking that the value returned from the comparator was being used as the priority and causing the sorting to be dependent upon the order in which the values were added... which wouldn't be much of a sort. And now I don't even know how I got to that conclusion.

TQ: what was the purpose of keeping the cards in a queue rather than a set or other collection?

Trick Question
Apr 9, 2007


The main purpose was that i could just import the priorityQueue and it'd auto-sort real easy.

Adbot
ADBOT LOVES YOU

RitualConfuser
Apr 22, 2008
What I'm getting at is that using a queue would suggest that the cards are going to be queued and then dequeued at some point. But, it seems like you'd probably want to iterate through the hand multiple times, and as rjmccall and Surface said, you can't iterate through the items in a PriorityQueue in sorted order without dequeueing them. So, if you need the ability to iterate through the cards multiple times (in order), then it's probably not the right structure.

RitualConfuser fucked around with this message at 08:43 on Dec 10, 2010

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