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
Contra Duck
Nov 4, 2004

#1 DAD
You didn't give us the code for DoubleListnode so it's possible that class is performing some actions I'm not aware of, but at a glance the constructor looks wrong.

code:
    /**
     * Create a new, empty list.
     */
    public SimpleLinkedList() {
        head = new DoubleListnode<E>(null, null, tail);
        tail = new DoubleListnode<E>(head, null, null);
    }
On the first line 'tail' hasn't been initialised yet so head's next element is still set to null. Since get(int) and size() start at the head and count forward, you're not finding anything because the head element doesn't have a next node. Fix that one first, then start looking for other problems further down the line.

Adbot
ADBOT LOVES YOU

epswing
Nov 4, 2003

Soiled Meat
Just a style gripe, but this:

code:
    public boolean hasNext() {
    	boolean retval = true;
    	if (curr.getNext() == null || curr.getData() == null) {
    		retval = false;
    	}
        return retval;
    }
is the same as this:

code:
    public boolean hasNext() {
        return !(curr.getNext() == null || curr.getData() == null)
    }
Edit: vvv Agree with Fly

epswing fucked around with this message at 07:06 on Mar 9, 2010

Fly
Nov 3, 2002

moral compass

epswing posted:

Just a style gripe, but this:

code:
    public boolean hasNext() {
    	boolean retval = true;
    	if (curr.getNext() == null || curr.getData() == null) {
    		retval = false;
    	}
        return retval;
    }
is the same as this:

code:
    public boolean hasNext() {
        return !(curr.getNext() == null || curr.getData() == null)
    }
Style but also clarity. I was going to post almost the same thing, avoiding the negation.
code:
    public boolean hasNext() {
        return (curr.getNext() != null) && (curr.getData() != null)
    }

yatagan
Aug 31, 2009

by Ozma
Jumping on the style train, I prefer this way because I think it's easiest to parse reading someone else's code. Some people might lambast multiple points of return, but the reason that's undesirable is not applicable here.

code:
    public boolean hasNext() {
        if (curr.getNext() == null || curr.getData() == null) {
            return false;
        }
        return true;
    }

DaNerd
Sep 15, 2009

u br?
I've written a short program that randomly generates a String between 1 and 8 characters in length.

What I would like to do is find some way to check if that String is an English word without using a crawler on dictionary.com. Manually coding a class with every word in the English language is not an option.

I'm just looking to see if anyone has a suggestion for this, or knows of/has a class that does something similar to this already...

DaNerd fucked around with this message at 08:57 on Mar 9, 2010

yatagan
Aug 31, 2009

by Ozma

DaNerd posted:

I've written a short program that randomly generates a String between 1 and 8 characters in length.

What I would like to do is find some way to check if that String is an English word without using a crawler on dictionary.com. Manually coding a class with everyone word in the English language is not an option.

I'm just looking to see if anyone has a suggestion for this, or knows of/has a class that does something similar to this already...

Jazzy or Suggester Spellcheck.

epswing
Nov 4, 2003

Soiled Meat

yatagan posted:

Jumping on the style train, I prefer this way because I think it's easiest to parse reading someone else's code. Some people might lambast multiple points of return, but the reason that's undesirable is not applicable here.

code:
    public boolean hasNext() {
        if (curr.getNext() == null || curr.getData() == null) {
            return false;
        }
        return true;
    }

Sorry, I fail to see how this offers any readability advantages. You should be able to read simple boolean expressions, so "return A || B" should be very clear. You sound like you'd write something like...

code:
    public boolean isEmpty() {
        if (list.size() == 0)
            return true;
        } else {
            return false;
        }
    }
...which is just painful, and should be return list.size() == 0 of course.

If the expressions were getting particularly complex, you could do something like...

code:
    public boolean hasNext() {
        boolean nextIsNull = curr.getNext() == null,
                dataIsNull = curr.getData() == null;
        return (nextIsNull || dataIsNull);
    }
...but even that is pushing it.

yatagan
Aug 31, 2009

by Ozma

epswing posted:

You should be able to read simple boolean expressions, so "return A || B" should be very clear.

I agree, but this is return !A && !B, which takes me a second to parse.

code:
return (curr.getNext() != null) && (curr.getData() != null)
It's not a big deal and I've written code that looks like it, I just think it's slightly less easy to read than what I did. For your isEmpty() method, I would definitely just use "return list.size() == 0".

Max Facetime
Apr 18, 2009

epswing posted:

code:
    public boolean hasNext() {
        boolean nextIsNull = curr.getNext() == null,
                dataIsNull = curr.getData() == null;
        return (nextIsNull || dataIsNull);
    }
...but even that is pushing it.

Yeah, don't do this mechanically. nextIsNull doesn't tell anything more than curr.getNext() == null. In this context, you could name them

     boolean isLastNode = curr.getNext() == null;
     boolean isFirstOrLastNode = curr.getData() == null;

which gives

     return isFirstOrLastNode || isLastNode;

which suggests there is a design problem.

Brain Candy
May 18, 2006

yatagan posted:

I agree, but this is return !A && !B, which takes me a second to parse.

DeMorgan's laws should be burned into your brain.

yatagan
Aug 31, 2009

by Ozma

Brain Candy posted:

DeMorgan's laws should be burned into your brain.

Well it's still !(A || B), which would also take me a second to parse. I have a "thing" for code that reads like I would say the process out loud.

epswing
Nov 4, 2003

Soiled Meat
The code you posted contained a boolean expression with ANDs/ORs/NOTs, so I'm not sure what you're arguing now. I wasn't griping about negations, I was squinting at multiple return statements.

yatagan
Aug 31, 2009

by Ozma

epswing posted:

The code you posted contained a boolean expression with ANDs/ORs/NOTs, so I'm not sure what you're arguing now. I wasn't griping about negations, I was squinting at multiple return statements.

It's a matter of how you would describe the process verbally and how the code reads straight through, left to right like you would read a paragraph. It's very awkward to try and read your return statements in this manner, but my code reads like an english sentence. You don't have to spare even a second to think about my statements, they just flow.

My version: If next is null or data is null return false, otherwise return true.
code:
        if (curr.getNext() == null || curr.getData() == null) {
            return false;
        }
        return true;
Your initial version: Return the opposite of whether next is null unless data is null, then return the opposite of whether data is null.
code:
return !(curr.getNext() == null || curr.getData() == null)
Revised reversion: Return whether next is not null if data is not null, otherwise return false.
code:
return (curr.getNext() != null) && (curr.getData() != null)

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.

yatagan posted:

but my code reads like an english sentence.
This is not a goal of programming or programming languages.

yatagan
Aug 31, 2009

by Ozma

Mustach posted:

This is not a goal of programming or programming languages.

You must like deciphering other programmer's work. The easier it is to read and decipher the logic, the easier it is to maintain. My goal is to write code that, in addition to meeting technical objectives, can be looked at by anyone and understood more or less immediately.

edit: I want to acknowledge this example is a trivial one, but it embodies the essence of what I consider the art and aesthetics of programming.

yatagan fucked around with this message at 17:17 on Mar 9, 2010

lamentable dustman
Apr 13, 2007

🏆🏆🏆

for what is worth I prefer yatagan's way of writing it but would of had a else so it lines up

:3:

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.

yatagan posted:

You must like deciphering other programmer's work. The easier it is to read and decipher the logic, the easier it is to maintain. My goal is to write code that, in addition to meeting technical objectives, can be looked at by anyone and understood more or less immediately.
You're conflating "understandability" with "reads like english." English is not a good model for programming, because expressing precise logic in English requires verbosity and verbosity masks the complexity. Your version is just as hard to understand as the second one, because they both use roundabout logic to express what is returned, plus the extra verbosity makes it look more complicated than it actually is. The third is the best because it's both concise and straightforward.

Examples of programming languages that try to read like English: COBOL and SQL. And they both suck because of it.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

this is java, can't bitch about being verbose when using java

yatagan
Aug 31, 2009

by Ozma

Mustach posted:

You're conflating "understandability" with "reads like english." English is not a good model for programming, because expressing precise logic in English requires verbosity and verbosity masks the complexity. Your version is just as hard to understand as the second one, because they both use roundabout logic to express what is returned, plus the extra verbosity makes it look more complicated than it actually is. The third is the best because it's both concise and straightforward.

Examples of programming languages that try to read like English: COBOL and SQL. And they both suck because of it.

As you point out, we do not want to type out full sentences when programming, and having a language based around that concept has not worked. Nevertheless, verbosity is the heart of modern programming practices and making them more like English has only increased the ease of understanding them.

For example, suppose we adhere completely to the idea that verbosity is bad. So perhaps instead of classes like "ArrayList" or "ObjectOutputStream" we should just use "AL" and "OOS"? Instead of a variable like "socketAddress" we can just use "x"! Clearly, verbosity is important to understanding in these instances, and I argue it is also important to achieving optimum clarity in our hasNext() method.

My version does not use roundabout logic, it uses the most straightforward logic possible, with a minimum of binary and unary operators. In terms of actual operations performed, it is tied with your favorite. You are free to disagree that it is easier to read, but I certainly find it so.

zootm
Aug 8, 2006

We used to be better friends.
Choosing the correct level of verbosity is an important part of programming, and quite a lot of the time people go for too-short over too-long. Really one should be aiming for "concise" or even "pithy" - names should be as short as possible while conveying clearly their purpose, but not shorter. Abbreviating words is rarely useful and damages comprehensibility. Piles of intermediate results with similar names are not useful*. "BlobGeneratingSingletonAccessorInstance"-type names often state the obvious many times over. The balance to strike is, as Mustach said, "concise and straightforward".

Java sometimes edges toward the "too-long" side but people need to learn that code should be easy to read, not easy to write, and if names are compressed too much they lose an instancy of comprehension that is much more important than a little horizontal space.

* I once worked in a company where there was a code standard saying that expressions to be passed to if statements were to be bound to a variable (so x == null gets bound to xIsNull then used as the condition in an if, on its own). This sort of obsession with naming everything means that so many names are in scope that the important ones get buried. When your expression is complex enough that it needs a name is really a matter for judgement, but a hard-and-fast rules are unlikely to ever work for this.

sonic bed head
Dec 18, 2003

this is naturual, baby!
I am having a very very annoying problem with struts2. Here is the relevant part of struts.xml

code:

		<action name="/">
			<result type="redirect">
				 <param name="location">/user_home</param>
			</result>
		</action>
		<action name="user_*" method="{1}" class="userAction">
			<result name="home">/content/jsp/userHome.jsp
			</result>
		</action>
I am trying to get it to that when someone goes to the root of this application, they are either invisibly or forcefully redirected to the home method of the user action. My preferred method would be to not have to change the url in the browser url bar, but I can if that's necessary.

I've tried using * in the first action name, but that gives me an infinite redirect loop. Basically, I don't know how to redirect to an action with a wildcard name. Any help would be greatly appreciated.

epswing
Nov 4, 2003

Soiled Meat

osama bin diesel posted:

for what is worth I prefer yatagan's way of writing it but would of had a else so it lines up

:3:

Agreed, I can more easily stomach it without the fall-through return statement. And for what it's worth, I'd read the following two statements aloud exactly the same way.

1. if (A || B) { return true; } else { return false; }
2. return (A || B);

amr
Feb 28, 2005
I love boxes of toast
Has anyone here used RMI before? I've got an assignment that requires passing objects around using RMI and it's a bit of a pain...

I've currently got it all in one project in eclipse, split up into packages with a 'common' package that has interfaces for the client & sever. And it seems to work OK... But before I get too deep in what I'm doing currently does anyone have any decent RMI resource/tutorial links? I've found a few basic ones that cover getting a client and server to work on the same machine, still in the IDE, but very few on actually exporting the code to a working JAR.

epswing
Nov 4, 2003

Soiled Meat
Exporting to jar shouldn't be too hard, eclipse can do that for you, you just specify the file with the main method you want to run. I think it's under File -> Export -> Export to JAR.

Someone asked about RMI recently, if you look back a few pages in this thread you might find some good links.

Fly
Nov 3, 2002

moral compass

yatagan posted:

Revised reversion: Return whether next is not null if data is not null, otherwise return false.
code:
return (curr.getNext() != null) && (curr.getData() != null)
For what it's worth this is the way I think about the return value. There's no distributive negation in it, and it's a simple conjunctive expression just like it should be---the simplest algrebraic expression we can use. We all practiced this in high school, right?

Now if there were ten terms in the expression, one might want to further abstract those, but programming with expressions normally seems more natural than programming with superfluous control structures and statements.


edit: A recent blog reviewed the old The Elements of Programming Style. I tend to agree with them Kernighan and Plauger:

quote:

Dont use conditional branches as a substitute for a logical expression.

Fly fucked around with this message at 16:52 on Mar 10, 2010

a slime
Apr 11, 2005

I have a list of integer message types that I want to map to strings. They will never change at runtime. I know about HashMap, but where is the idiomatic Java place to initialize it with all my poo poo

Max Facetime
Apr 18, 2009

not a dinosaur posted:

I have a list of integer message types that I want to map to strings. They will never change at runtime. I know about HashMap, but where is the idiomatic Java place to initialize it with all my poo poo

Put it all in a text file, then access it using a ResourceBundle. No initialization required.

If you really want to do it your way, then a static initializer block sounds about right.

Max Facetime fucked around with this message at 17:25 on Mar 10, 2010

chippy
Aug 16, 2006

OK I DON'T GET IT
I need a little help with some scroll bars. I'm working on an app which takes some text from a TextArea in a ScrollPane, clears the text box, processes the text and then refills the text box with the processed text (which is exactly the same length as the original text).

The issue I'm having is this: When there's not enough text to necessitate the scroll bars, it works well, and as the changed text is mostly the same as the original, you just see the bits that have been altered change in place. However if there's enough text for the scrollbars to be visible, as I'm writing the text back into the textbox with textArea.append, it causes to scroll to the bottom as the text is written back into it. It looks ugly and makes it a lot harder to compare with original text with the new text so I'm trying to store the scroll bar position before the operation and then restore it after like this:

code:
int vScroll = scrollPane.getVerticalScrollBar().getValue();
int vMax = scrollPane.getVerticalScrollBar().getMaximum();
int vMin = scrollPane.getVerticalScrollBar().getMinimum();
int vVisAmount = scrollPane.getVerticalScrollBar().getVisibleAmount();

String text = tabBox.getText();
tabBox.setText(null);

// do stuff to text

tabBox.append(text);

vScrollBar.setValues(vScroll, vVisAmount, vMin, vMax);
The reason I'm storing the min, max etc as well is because the API documents suggest that it's better to set all the values at once with setValues rather than just using setValue. I've tried it both ways. Anyway, according to the API setValues should fire all the necessary events to update the scroll bar properly, but it isn't working, it's just scrolling down to the bottom. If I print the 4 values to the command line before setting them, they all seem to be stored correctly. Can anyone tell me either how to update the scroll bar position properly, or alternately how to update the text in the box without causing scrolling?

chippy fucked around with this message at 01:55 on Mar 12, 2010

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
This is actually an Eclipse question (sorry), but I figured a huge portion of Java users use Eclipse.

Does anyone know of a calculator plugin for Eclipse that lets me evaluate simple math expressions easily while using the editor? The one plugin I could find was ECalculator and it sucks.

chippy
Aug 16, 2006

OK I DON'T GET IT

chippy posted:


// scrollbar stuff

If anyone's interested, I fixed this by using DefaultCaret.setUpdatePolicy to disable auto-scrolling before the update.

ToastedZergling
Jun 25, 2007

Chubby Walrus:
The Essence of Roundness
I'm looking for a way in java to surround words in a string with HTML span tags. For example:

Input:
"The quick brown fox jumps."

Outputs:
"<span>The</span> <span>quick</span> <span>brown</span> <span>fox</span> <span>jumps</span>."

I've taken a look at the Lucene SimpleHTMLFormatterp class but it seems to be a bit of overkill for what I'm trying to accomplish.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Why does this work fine the first time, but subsequent calls give me the "you must be a registered user to view this page..."

code:
public static String fetchPage(String urlString) {
	StringBuilder page = new StringBuilder();
	try {
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		conn.setRequestProperty("Cookie", "bbuserid=38563; bbpassword=editedout");
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			page.append(line);
		}
		reader.close();
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return page.toString();
}

String page = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");
			
String page2 = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");

yatagan
Aug 31, 2009

by Ozma

ToastedZergling posted:

I'm looking for a way in java to surround words in a string with HTML span tags. For example:

Input:
"The quick brown fox jumps."

Outputs:
"<span>The</span> <span>quick</span> <span>brown</span> <span>fox</span> <span>jumps</span>."

I've taken a look at the Lucene SimpleHTMLFormatterp class but it seems to be a bit of overkill for what I'm trying to accomplish.

code:
String baseString = "The quick brown fox jumps.";
String[] splitString = baseString.split(" ");
StringBuffer buffer = new StringBuffer();

for (String currString : splitString) {
    buffer.add("<span>");
    buffer.add(currString);
    buffer.add("</span> ");
}

String finalString = buffer.toString();

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

yatagan posted:

code:
String baseString = "The quick brown fox jumps.";
String[] splitString = baseString.split(" ");
StringBuffer buffer = new StringBuffer();

for (String currString : splitString) {
    buffer.add("<span>");
    buffer.add(currString);
    buffer.add("</span> ");
}

String finalString = buffer.toString();

It would probably be better to use a StringBuilder here as it's unsynchronized and goes out of scope immediately.

ToastedZergling
Jun 25, 2007

Chubby Walrus:
The Essence of Roundness
Yatagan, thanks for the help, but I was trying to avoid writing code, preferring instead to find a package that already addresses this need. While something as simple as your code or a regex may seem adequate at first glance, you have to take into consideration that there are numerous caveats not being considered, e.g. your code would capture the period in last word as "<span>jumps.</span> "

Considering there are a bunch of caveats, like hyphens, numbers, and other forms of punctuations, defining what constitutes a "word" and parsing accordingly is non-trivial, which would mean my post would deserve its own thread rather than this megathread.

tldr; I prefer leveraging existing frameworks than writing custom parsing

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE
Last time I needed to do anything with HTML I went the lazy route and used Groovy.
code:
String s = """<h1>${bob.name}'s awesome report!</h1>"""
Adds a decent amount of overhead though.

yatagan
Aug 31, 2009

by Ozma

ToastedZergling posted:

Considering there are a bunch of caveats, like hyphens, numbers, and other forms of punctuations, defining what constitutes a "word" and parsing accordingly is non-trivial, which would mean my post would deserve its own thread rather than this megathread.

Not really. http://en.wikipedia.org/wiki/Regular_expression

[^\w]

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

yatagan posted:

Not really. http://en.wikipedia.org/wiki/Regular_expression

[^\w]

This doesn't parse this sentence correctly ;)

\w corresponds to [A-Za-z0-9_] and will thus have issues with apostrophes, hyphens etc. Nonetheless, you can bang out a 90% solution with regexes without too much trouble. For something closer to 100%, you can write a grammar.

yatagan
Aug 31, 2009

by Ozma
Nevermind, misunderstood you. You can get much closer than 90% though with regex I bet.

Adbot
ADBOT LOVES YOU

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip
Oh hurr mental parse failure

Also, does java support \W as the class of non-word characters or is that a perlism that hasn't caught on in javaland

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