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
Rohaq
Aug 11, 2006
Well okay, I'll keep that in mind in future.

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Rohaq posted:

Err, why? It's just a formatting choice, and CamelCase can be used either the first letter capitalised or not.

Because that's what you do in Java. Adopt whatever naming convention is used by whatever language you happen to be using so people don't look at your code and go "WTF?".

Rohaq
Aug 11, 2006

fletcher posted:

Because that's what you do in Java. Adopt whatever naming convention is used by whatever language you happen to be using so people don't look at your code and go "WTF?".
Well jeez, sorry. I've just started in Java, and I've never seen a programming language where its users/maintainers actually attempt to enforce a particular formatting standard for names; I've always just used CamelCase with the first letter lowercased for my own projects, or if I'm working on somebody else's code, adopt whatever standard that they've used in their code to keep the code consistent and more readable.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Rohaq posted:

Well jeez, sorry. I've just started in Java, and I've never seen a programming language where its users/maintainers actually attempt to enforce a particular formatting standard for names; I've always just used CamelCase with the first letter lowercased for my own projects, or if I'm working on somebody else's code, adopt whatever standard that they've used in their code to keep the code consistent and more readable.

FWIW, Python (the only other language I'm familiar with) also has a standard for names formatting.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Rohaq posted:

Well jeez, sorry. I've just started in Java, and I've never seen a programming language where its users/maintainers actually attempt to enforce a particular formatting standard for names...

Are you using any kind of IDE? If not, I realize it adds a little bit to the learning curve at the beginning, but it's a bigger pay-off in the end: for example, in Eclipse, it would have given you warnings about the casing of your class name.

One of Java's biggest strengths are things like Javadoc, which are hooks built into the specification that facilitate documentation of code and conveyance of that documentation. Thusly, consistency in styling lends itself toward improved documentation, which results in better understanding by others. I don't mean to jump down your throat (and apologize if it came off that way) - styling habits can be difficult to change later in development, and establishing good habits earlier makes it easier for you to later maintain the code you write now.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Rohaq posted:

I've just started in Java, and I've never seen a programming language where its users/maintainers actually attempt to enforce a particular formatting standard for names; I've always just used CamelCase with the first letter lowercased for my own projects

(sorry if this seems like piling on)

It's important to note that most naming conventions apply different rules to different kinds of things. For example, the standard Java convention does use the capitalization convention you describe (nameOfThing), but only for variables, method names, and fields; classes are always initial-caps (NameOfThing), and enumerators use all-caps with underscores (NAME_OF_THING).

The convention that types are spelled NameOfThing is increasingly universal; the only major exceptions are C and environments (like the C++ STL) that strive for consistency with C. Somewhat less pervasive, but still dominant, is the convention that variables are written nameOfThing. I wouldn't say there's any sort of emergent consensus on how to name functions, methods, fields, and enumerators, though of course specific communities usually have standards.

Rohaq
Aug 11, 2006

Chairman Steve posted:

Are you using any kind of IDE? If not, I realize it adds a little bit to the learning curve at the beginning, but it's a bigger pay-off in the end: for example, in Eclipse, it would have given you warnings about the casing of your class name.

One of Java's biggest strengths are things like Javadoc, which are hooks built into the specification that facilitate documentation of code and conveyance of that documentation. Thusly, consistency in styling lends itself toward improved documentation, which results in better understanding by others. I don't mean to jump down your throat (and apologize if it came off that way) - styling habits can be difficult to change later in development, and establishing good habits earlier makes it easier for you to later maintain the code you write now.
I'm using Netbeans, which didn't warn me of any issues. I've used it to refactor the loader class into Loader now anyway. I've not had to work on many projects with others, so I've always assumed that code styling was down to personal preference.

Thermopyle posted:

FWIW, Python (the only other language I'm familiar with) also has a standard for names formatting.
I did not know that; I've just started in Python too for another project: Thank you university! On the plus side, I'm now versed in multiple languages, just not in any great depth.

rjmccall posted:

(sorry if this seems like piling on)

It's important to note that most naming conventions apply different rules to different kinds of things. For example, the standard Java convention does use the capitalization convention you describe (nameOfThing), but only for variables, method names, and fields; classes are always initial-caps (NameOfThing), and enumerators use all-caps with underscores (NAME_OF_THING).
Oh Goddamnit, I've got an enumerator in my code too. Back I go!

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Rohaq posted:

Oh Goddamnit, I've got an enumerator in my code too. Back I go!

Just to make sure it's clear: the proper declaration of an enum is a mix of camel case and all caps:

code:
public enum ThisIsAnEnum {
OPTION_ONE,
OPTION_TWO;
}

maskenfreiheit
Dec 30, 2004
Edit: Double Post

maskenfreiheit fucked around with this message at 21:32 on Mar 13, 2017

epswing
Nov 4, 2003

Soiled Meat
It needs to be public static void test() since you're calling it from main(), which indeed does need to be static itself. But then if you do that, then the methods test() calls also need to be static, and the variables those methods reference also need to be static, and so on.

So...

Either make everything static, OR (this is the Right Thing to do) leave everything as is and just change the contents of main() to:
code:
	public static void main(String[] args)
	{
		mangler m = new mangler();
		m.test();
	}
E: You should also think about renaming mangler to Mangler. Classes generally have CamelCase names.

epswing fucked around with this message at 00:39 on Jan 3, 2011

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I'm just learning Java now and I'm wondering what's something good for parsing HTML? I'm mostly used to BeautifulSoup for Python...

Thermopyle fucked around with this message at 03:04 on Jan 3, 2011

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Thermopyle posted:

I'm just learning Java now and I'm wondering what's something good for parsing HTML? I'm mostly used to BeautifulSoup for Python...
I've been using Jericho, but I have no idea how good it is in general.

Edit: Or maybe jsoup

Malloc Voidstar fucked around with this message at 05:37 on Jan 3, 2011

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

GregNorc posted:

Help?
As well as what epswing said, it'd probably be easier to use String's replace() method instead of all that stuff with arrays and substrings etc.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Also don't ever do anything like this:

code:
		String s = "";
		for (int i = 0; i < sArray.length; i++)
		{
			s += sArray[i];		
		}
Because Strings are immutable, so every iteration is an object creation involving copying the previous String.

Malfeasible
Sep 10, 2005

The sworn enemy of Florin

Aleksei Vasiliev posted:

Also don't ever do anything like this:

code:
		String s = "";
		for (int i = 0; i < sArray.length; i++)
		{
			s += sArray[i];		
		}
Because Strings are immutable, so every iteration is an object creation involving copying the previous String.
...

Just to elaborate on this:

The JVM keeps a kind of String pool and will not usually instantiate a brand new String if it knows it already has an equivalent String available, but you can crowd your String pool with abandoned Strings which eats up RAM.

StringBuilder and StringBuffer are mutable without abandoning the old Object and cluttering up any kind of Object pool.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Malfeasible: In theory you can further improve performance by creating a StringBuilder of the right size off the bat (new StringBuilder(int capacity)), but the difference is very small compared to not using a StringBuffer/StringBuilder.

StringBuffers differ from StringBuilders in that they are thread-safe- this also makes them slightly slower. If only one thread touches it (which is usually the case), use a StringBuilder.

Finally, remember that for a single expression like "abc"+"def"+"g" the JLS specifies that the overloaded + operator uses a StringBuilder, so there's no need to go crazy and do every string concatenation by hand, just the ones that are part of a loop body.

Paolomania
Apr 26, 2006

Internet Janitor posted:

StringBuffers differ from StringBuilders in that they are thread-safe- this also makes them slightly slower.

This. If you diff the source the only real difference is a "synchronized" on the front of every funciton. This means that at runtime the JVM will do some extra operations to wait for, acquire, and release the monitor for a StringBuffer before and after every method call.

Smeg Head
Apr 22, 2010
How do I pass an int value e.g int bullet = 1; into another class in Java?

Bit more of an explination.

Got 4 if statements - When one of them is chosen, it will make bullet equal either 1,2,3 or 4.

The program then changes screens and moves to another, seperate class. This class needs to use the value of bullet to determine a few simple things.

How do I get the value of bullet from one class into another ?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Smeg: I believe what you're looking for is a method call. Methods can take arguments. One method can call another and supply values as arguments. It might help to start at the beginning of the Java Learning Trail and work your way there.

Rohaq
Aug 11, 2006
What am I doing wrong here?

code:
conn = (HttpConnection) Connector.open(inUrl);
input = conn.openInputStream();
long len = conn.getLength();
long currLen = 0;
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int chr;
while ((chr = input.read()) != -1) {
  bytestream.write(chr);
  if ( len != -1 ) {
  currLen = bytestream.size();
    try {
      gaugeValue = (int) Math.floor((currLen / len) * 100);
    } catch ( ArithmeticException e ) {
      gaugeValue = 0;
    }
  } else {
    gaugeValue = -1;
  }
}
strOut = new String (bytestream.toByteArray());
bytestream.close();
On the line
code:
gaugeValue = (int) Math.floor((currLen / len) * 100);
gaugeValue always ends up being equal to 0. If currLen = 1000 and len = 10000, then Math.floor((currLen / len) * 100) should return 10.00, shouldn't it?

J2ME here, so J2ME related suggestions, please!

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Rohaq: longs are an integer type. long/long will truncate, so 1000/10000 = 0.

Rohaq
Aug 11, 2006

Internet Janitor posted:

Rohaq: longs are an integer type. long/long will truncate, so 1000/10000 = 0.
Oh goddamnit. Is there are alternative solution for my percentage calculating needs?

EDIT:- Never mind, I shall not be so lazy; going to try casting, or just using doubles.

DOUBLE EDIT:- Setting len and currLen to doubles works just fine, thanks for pointing out my obvious mistake!

Rohaq fucked around with this message at 01:42 on Jan 4, 2011

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
You could also store values in fixed-point by either multiplying by a power of 10 or just shifting left depending on what sort of precision you'd like and then remembering to renormalize before you use them for something. Doubles are probably a better solution.

edit: VVV I'd use a cast, but that works just as well.

Internet Janitor fucked around with this message at 02:00 on Jan 4, 2011

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Rohaq posted:

Oh goddamnit. Is there are alternative solution for my percentage calculating needs?

EDIT:- Never mind, I shall not be so lazy; going to try casting, or just using doubles.

DOUBLE EDIT:- Setting len and currLen to doubles works just fine, thanks for pointing out my obvious mistake!
gaugeValue = (int) Math.floor((currLen * 1.0 / len) * 100);

Scaevolus
Apr 16, 2007

gaugeValue = (int)((currLen[b] * 100) / len);

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

As mentioned earlier, I'm just learning Java and I'm hoping someone can glance at this and talk to me about some design/implementation.

I'm planning on running ThreadedDownloader() in it's own thread from my own app. When my app wants it to download something, it'll add a new url and download destination via addUrl(). When ThreadedDownloader() sees that there's urls to be downloaded, it starts a new thread running ThreadedDownload() which then gets the oldest item in downloadUrls and downloads it.

1. Good design?
2. Am I structuring this right? ThreadedDownload() is nested in ThreadedDownloader() is nested in Download() largely because it helps me with my mental model of how the app works.
3. Specifically on line 38...is the best way to start the new thread?
4. Any other pointers?

Thanks!

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Thermopyle posted:

As mentioned earlier, I'm just learning Java and I'm hoping someone can glance at this and talk to me about some design/implementation.

Thanks!
A (ordered) set of objects containing the two strings seems more logical to me than a hashtable here (implement .equals to only compare the URL if you want URLs to be unique).

You could also consider using an ExecutorService to manage the download tasks.

edit: Also, the 3rd accessor method doesn't seem complete.

edit2: Also consider datastructures like this, which may make things like getting the oldest item easier.

ShardPhoenix fucked around with this message at 00:41 on Jan 5, 2011

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

ShardPhoenix posted:

A (ordered) set of objects containing the two strings seems more logical to me than a hashtable here (implement .equals to only compare the URL if you want URLs to be unique).

Yeah, that was just something I threw in their quickly to get the idea across.

ShardPhoenix posted:

You could also consider using an ExecutorService to manage the download tasks.

Thanks, this looks like something I'd be interested in.

ShardPhoenix posted:

edit: Also, the 3rd accessor method doesn't seem complete.

Yeah, I didn't bother with it as the hashtable was just temporary to get the idea across.

ShardPhoenix posted:

edit2: Also consider datastructures like this, which may make things like getting the oldest item easier.

Again, something useful! Thanks.

Contra Duck
Nov 4, 2004

#1 DAD

ShardPhoenix posted:

You could also consider using an ExecutorService to manage the download tasks.

This is what I would suggest too. Use one of the static methods in Executors to create an ExecutorService and then pass in Runnable objects to perform the downloads. ExecutorServices basically do everything you're trying to do here without the subtle multithreading-related bugs.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
This isn't so much a Java question as it is a general programming/algorithm question. But I'm coding in Java so here I ask.
Feel free to redirect me somewhere.

With a Bejeweled-clone game like this, how would I efficiently (not bruteforce) find matches moves I could make to match gems? Or rather, how do I learn how to write a thing to efficiently find matches moves?
Image recognition isn't the problem I'm having; I'm not bothering to work on that until I can write the actual important part.

I am bad at efficiency :(


edit: By the way, Puzzle Quest is a really good RPG/casual-puzzle hybrid.

Malloc Voidstar fucked around with this message at 04:20 on Jan 5, 2011

epswing
Nov 4, 2003

Soiled Meat
Define "match".

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

epswing posted:

Define "match".
Any of these moves is valid. Maybe more, that was a quick glance.

Specifically: 3-of-a-kind, 4oak, 5oak, combinations of those (making two 3oaks at the same time), some matches are more important (for 3oaks: +5 skulls > skulls > gems > gold == experience (purple)).
Horizontal and vertical only.

edit: more example moves, different field. Multiplier-yellow-yellow-yellow is the best immediate move here, being 4oak. Multipliers match gems.

Malloc Voidstar fucked around with this message at 03:40 on Jan 5, 2011

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Aleksei Vasiliev posted:

This isn't so much a Java question as it is a general programming/algorithm question. But I'm coding in Java so here I ask.
Feel free to redirect me somewhere.

With a Bejeweled-clone game like this, how would I efficiently (not bruteforce) find matches? Or rather, how do I learn how to write a thing to efficiently find matches?
Image recognition isn't the problem I'm having; I'm not bothering to work on that until I can write the actual important part.

I am bad at efficiency :(
I've implemented a Bejewelled clone before in Ruby. I don't have the code immediately handy, but in pseudocode it was something like this (assuming the game model is a 2d array of objects representing the jewels):

code:
for each row in grid
    for i in row
        if (row[i].color == row[i+1].color == row[i+2].color)
            row[i].marked = true
            row[i+1].marked = true
            row[i+2].marked = true

<do the same for columns>

<remove all marked gems, tally score based on number and type removed>
This correctly marks matches of any length greater than or equal to 3. I don't know if there's a simple faster way to do it, but this was essentially instantaneous even in Ruby (which is 50x slower than Java). I'm not sure what you would use image recognition for here.

ShardPhoenix fucked around with this message at 04:13 on Jan 5, 2011

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

ShardPhoenix posted:

I'm not sure what you would use image recognition for here.
I'm writing a bot to play the game, not writing a game. Hence the image recognition I'll eventually need. So I'm not checking "are there matches on the current board", but rather, "what are matches I could make given a board". My wording was probably ambiguous, sorry.

The reason I don't want to use bruteforce is I'm planning on making it think at least one move in advance; not just playing a move based on the current board, but choosing what to swap based on what will happen if that match is chosen. Swapping a gem, seeing if it made matches, swapping next gem, seeing if it made matches, etc. would be inefficient and probably make it not work well at all.
(The Bejeweled-clone game I'm playing has an AI opponent who is working on killing you, so it's bad to give it good matches)

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Aleksei Vasiliev posted:

I'm writing a bot to play the game, not writing a game. Hence the image recognition I'll eventually need. So I'm not checking "are there matches on the current board", but rather, "what are matches I could make given a board". My wording was probably ambiguous, sorry.

The reason I don't want to use bruteforce is I'm planning on making it think at least one move in advance; not just playing a move based on the current board, but choosing what to swap based on what will happen if that match is chosen. Swapping a gem, seeing if it made matches, swapping next gem, seeing if it made matches, etc. would be inefficient and probably make it not work well at all.
(The Bejeweled-clone game I'm playing has an AI opponent who is working on killing you, so it's bad to give it good matches)
Just try every possible move and see if you can get that fast enough. It might not be that bad, especially since you can ignore any moves that don't make a match (ie most of them) on the second iteration.

The other way I guess would be to do it in reverse - find 1-gappers and see if there are any jewels that can swap in. That would be more complicated though and I don't know if it would be that much faster.

ShardPhoenix fucked around with this message at 04:27 on Jan 5, 2011

fart factory
Sep 28, 2006

SHREK IS COOL
I'm having an issue with a broken pipe exception within a java program. The exception occurs when the server recieves an unusually long xml message. I've read that this can cause the broken pipe because the writing thread has already finished by the time the reading thread has processed the message and sent the response. Some sort of countdown latch has been proposed, but the thread that is writing the data to the server is part of a different project. Is there any other way to ensure that the thread will stay running until all the data has been read/response has been sent?

VanityHero
Mar 10, 2009

by Ozmaugh
Trying to learn Java with absolutely no programming experience, what books would be best to start on? also on that note, would I be shooting myself in the foot if I learned of a 5.0 book?

tef
May 30, 2004

-> some l-system crap ->
Starting with 5 is a good idea. I can't recommend any beginner java books off hand but I will say that 'Effective Java 2nd ed' is an excellent second book.

chippy
Aug 16, 2006

OK I DON'T GET IT
Thinking in Java is also very good, especially as an introduction to object-oriented principles in general.

Adbot
ADBOT LOVES YOU

Paolomania
Apr 26, 2006

fart factory posted:

I'm having an issue with a broken pipe exception within a java program. The exception occurs when the server recieves an unusually long xml message. I've read that this can cause the broken pipe because the writing thread has already finished by the time the reading thread has processed the message and sent the response. Some sort of countdown latch has been proposed, but the thread that is writing the data to the server is part of a different project. Is there any other way to ensure that the thread will stay running until all the data has been read/response has been sent?

It is not that difficult to make a thread wait around for some condition, but without more specifics about your programs and how much control you have over each side of the pipe (do you control both the client and server code? are you using HTTP or some ad-hoc XML protocol?) it is hard to make a recommendation.

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