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
Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Doctor w-rw-rw- posted:

Jersey. I myself am partial to Dropwizard for tinkering with REST stuff, which is a nice streamlined package of a lot of useful libraries and configuration.

Second this, I just started a REST project at work and I'm using Jersey and loving it. Although all the really JAX-RS compliant implementations have almost identical annotations and API, so you can really swap between them. (RESTEasy, Apache CXF, Wink, Restlet although its a bit different because it was developed when JAX-RS wasn't fully finished)

Jersey makes it pretty painless to get a REST web service to do whatever you want. And it plays nice with Tomcat.

For unit testing, I wrote a simple client using the jersey.api.client.Client and have some JUnit tests. I also have a browser thingy to do automated testing that way, but I don't use it for REST as much as I do other projects, I'm just passing JSON which is easy to respond to programatically.

Spring MVC is indeed very heavyweight, seemed like way overkill to me.

If it matters I just reviewed all of these for work and concluded Jersey would be the best. :thumbsup:

Zaphod42 fucked around with this message at 16:18 on Jul 5, 2013

Adbot
ADBOT LOVES YOU

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Stabbey_the_Clown posted:

Tomcat 7 says that it is started and running, but http://localhost:8080/ is giving me a (Tomcat-generated) 404. I swear this poo poo was working the other day. I have no idea why it isn't working now. Tomcat is clearly running, it's generating the 404 message, so why can I not see it (or any other html or jsp page) that are in the webapps\ROOT directory?

For starters, try clearing the work folder in tomcat and make sure that webapps folder has permissions set correctly, toss a chmod -R 777 in there.

After that, any errors in the tomcat logs?

Also double check what the expected URL should be. Probably http://localhost:8080/<webapp foldername>/

The trailing slash can be important, if /<foldername> doesn't work makes sure you try /<foldername>/

Zaphod42 fucked around with this message at 15:58 on Aug 1, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

supermikhail posted:

YES!

So I think I've finally pinned down the directory that the running jar is in. It involves StackOverflow's notes in the margins and
code:
ClassLoader.getSystemClassLoader().getResource(".").toURI()
Anything funny about that? (as in, dangerous to the health of computers close to me)

That's standard code for getting the working directory, its very common. It won't do anything dangerous in of itself, but as you said, you're getting files, so there's a chance you try to grab something afterwards and overwrite it or whatever.

This is running in a browser, right? If so you're pretty drat safe, unlikely user would have anything to do with those folders.

If you wanna be extra careful just give it a fairly unique filename, and you've done your due diligence.

Zaphod42 fucked around with this message at 22:23 on Sep 26, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

KildarX posted:

So I got an assignment to do up a password checking system, and by doing research I came on Regex's, and was wondering what I was doing wrong with them. Here's a sample part of the code.

Java code:

import java.util.regex.Matcher;

System.out.println("Please input a password, passwords must have atleast 8 characters, one upper and lower case letter, and one digit");
      
     do{

        //maybe system.out.println here instead so it says it every loop?

	String pwd = scan.next(); //THIS GOES HERE
          
        if (pwd.matches("[A-Z]"))
        {
            valid = true;
        }
     
         else
        {
            valid = false;
        }
}
while (valid == false); //AND THIS, but you got that one
Pretty much there are three or four areas where it's supposed to check if the string has upper, lower, and digits, and if the expression is still true it out puts a message saying "good work", the problem is I don't think it's working out properly, it's compiling but the code itself isn't working properly.

Edit: I am a goddamn re-re :eng99: I should have set while valid = false. Still doesn't work right when trying to give it a bad answer.

First, you need to get a new input on every iteration of the loop, or they can't correct a bad password.

Next, are you expecting pwd.matches("[A-Z]") to be (it's supposed to check if the string has upper, lower, and digits) ?

That's just a sign

You're going to want somethin more like [A-Za-z0-9] for all chars, but that's just matching a single character, so it needs to be [A-Za-z0-9]+ . But that's any number of characters, and doesn't guarantee all 3 are present. You need to go back to the regex drawing board.

:ssh: Something like (?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).{8,} although that's probably not exactly right

You can make the regex simpler if you use some java, you can just say if(string.length == 8 && string.matches("REGEX")) and not worry about that part in the regex.

Zaphod42 fucked around with this message at 23:03 on Oct 3, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

pigdog posted:

There's your problem.

No it isn't, he already pointed that one out, and I already pointed out other problems his code has.

KildarX posted:

Edit: I am a goddamn re-re :eng99: I should have set while valid = false. Still doesn't work right when trying to give it a bad answer.

Edit: whoops, your'e right, that's assignment. Still, he has other issues.

Zaphod42 fucked around with this message at 23:00 on Oct 3, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

rhag posted:

Oh, ok, so some flags then should solve the problem:
code:
        boolean containsUnderscore = false;
    	boolean containsUppercase = false;
    	for(char c: ch){
    		containsUnderscore |= c=='_';
    		containsUppercase |= Character.isUpperCase(c);
    	}
    	

Your first solution was very naive. This one's still not right, add another flag for numerics, then add an if() check to make sure its not too short and not too long, and then you'd have solved it. Good job not reading the requirements at all. :colbert: If you're not going to take the time to read the problem, just don't post, somebody else will get around to it (we already did)

But I assumed he was trying to learn regexes, and they're worth learning, but he's way off.

KildarX posted:

Thanks for the help guys been working on it steadily.

So here's my code, and I got two problems, it seems that the regex isn't actually checking everything[I looked up the regex of someone who had the same requirements], it's checking for at least one case, flipping valid to true and going on, the second problem is when I am using the comparison between confirm and pwd it's giving me a null pointer? Any help?

Okay you're still making the = and == mistake. Testing equivalence and setting equality are very different concepts and you need to learn the difference and be careful about their usage.

Don't just look up regexes, its time for you to sit down and learn the syntax. It takes awhile, but its worth doing. Otherwise just stay away from regexes entirely and use the language you're in to manually check it. Its not worth copy & pasting, you need to understand your own code. You're currently coding by guess & check, and that doesn't teach as much. It seems like you're new to java; if you're learning java right now you should just focus on that and learn regexes later when you're comfortable with java.

You're getting a nullpointer because pwd has dropped out of scope. (Its gone, its been deleted by that point)
You need to read about scope. Pwd needs to be defined outside of the do-while if you want to use it after the do-while.

Earlier on, say:
String pwd; //this defines pwd

Then inside the loop you can say:
pwd = scan.next(); // this sets your previously defined variable pwd to input
//if you define the variable here, it only exists within the scope of the loop

That way after the loop pwd still exists.

Also note that the way your system works, if they make a typo in entering their password the first time, it will loop forever until they enter their password again with the typo. They may not know what the typo was. So instead of doing (loop forever until get decent password), (loop forever until match), you need to do them within the same loop, a single (loop and get pass, then ask for another input and match) that way on each iteration of the loop, it asks for a new pass AND confirmation.

Zaphod42 fucked around with this message at 17:08 on Oct 4, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

KildarX posted:

:eng99: and I thought I was being clever.

edit: and done! Thanks everyone for your patience with my shenanigans.

You're getting better! However, I'm surprised it works... it shouldn't. This is a bug:

Java code:
	for (char array : pwd.toCharArray()) {
         if (Character.isUpperCase(array)) {
              valid = true;
         }
         else
         {
            valid = false;
         }
       
       }
Your logic is good here, we're looping through all the characters of the string and checking them. That's a good approach.
The problem here is it sets valid = true, but then if it later finds a character that is lower case, it sets it back to false again, overwriting the true.

So as long as the last valid=true; gets called on the last character, the password is perceived as valid. That's wrong. So a password of 1903348 would be true, since the last check for numbers is true, even though it was previously false since there are no uppercase or lowercase letters. This is why you need to test your program with valid and invalid inputs to make sure it doesn't false-positive.

The reason why it works when it shouldn't is because all 3 are setting valid to true and to false and back to true and back to false, and as long as it ends up true you accept it as true. You either need to have multiple different booleans, isUpperValid = false; then
if(isUpperCase()){ isUpperValid = true; }

And at the end you can check if isUpperValid && isLowerValid, etc.

Or even simpler, have just a single valid. But now you'll need to default to true, just set valid = true; by default, and then
if(isUpperCase()){ valid = false;}.

That way if it never overwrites it, it falls through. It sets it as true initially, but if any condition fails, that condition sets it to false. You have to be careful that one doesn't overwrite the behavior of the last.

If you want to be efficient, you can have the loop check if valid = true/false and stop looping if its already found a character.

As for checking the length, just use (pwd.length > 8) or whatever you need. Javadocs are your friends, as another goon said.

Googling the name of a class along with "java" will get you the javadocs most of the time. Googling "java string" I got:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
This describes what a String is, all of its public fields and public methods and what they return and what parameters they have.

These are the tools a String provides you already. Use them. :)

Zaphod42 fucked around with this message at 18:42 on Oct 4, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

KildarX posted:

Using Blue J, which doesn't have auto formatting that I can see. I use it, because it is extremely bare boned, and the UI for most UDKs make me cry with the amount of buttons and such to set up just a simple class and compile it.

It takes 2 buttons to make a class and compile it in Eclipse. (New Class button, Run Program button)

I will give you that Eclipse has tons of buttons that newbie programmers will never use, but you can just ignore them. Alternatively, you can create your own Eclipse perspective (call it 'clean java' or something) and simply remove all the controls you don't want.

You can literally customize Eclipse to just be a single text window if that's all you want. You can also open and close different windows and drag around where on the GUI they go. Its very flexible.

But you can always code in vi or emacs or notepad or whatever the hell and compile manually like back in the day, whatever works for you.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

carry on then posted:

Constructors always return a reference to a new instance of the class, so no.

Proof:


One last thing I should add, according to http://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java you can only chain once and it has to be the first line in the constructor.

Super calls to constructor should always be the first line anyways as a matter of habit.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Adventure Pigeon posted:

I've done a good bit of testing of the rendering part itself, but when I throw it with everything else it doesn't work. The problem is creating an appropriate smaller dataset will take a good bit of time, and I was originally expecting that getting it rendered wouldn't take as much time as it has. If I don't have something by tomorrow, that's what I'll work on doing though.

Edit: It works! Thank you very much Max Facetime. This drat thing has been driving me nuts for the better part of a week (though a lot of that was just programming the data processing bits). Now that this is done I can move on and make myself miserable with the next task.

If your problem was a null pointer in a constructor, it seems like you had a problem independent of the data set (you did) so testing without the full data was exactly what you should be doing.

If creating an "appropriate" smaller dataset would take too long, can you test it with an inappropriate one? Simply giving it a solid black or solid white texture would work to test your constructor.

Being able to quickly iterate on testing, debugging, and writing fixes is huge in programming. You'll solve your problems yourself and much quicker if you do.

If you had a problem in the rendering, then yeah, you'd need a data set to test. (Even then though a solid white texture could tell you lots of information). Even then, getting a smaller one is ideal. But your problem wasn't even in the rendering at all, it was in the setup of the JFrame (and lack of a main() )

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

rhag posted:

There is this fangled thing called unit testing. It apparently helps with ... testing your code. And you don't even need a main method. May need to think a bit about the design of the code, but otherwise ... it just works. and most of the IDEs and build systems have a pretty good support for JUnit or TestNG (two major libraries that allow you to do this), and they can even run them automatically, generate reports, etc.

Unit testing is pretty cool, should check it out someday.

Test Driven Development is the way to go :thumbsup:

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

StrikerJ posted:

I'm trying to write a method (method1) that draws a Swing window with a JTextField. And when the user enters something in the textfield and presses 'enter', the method returns that text that was written by the user.

My problem is that when I set an ActionListener on the JTextField (as in 'mytextfield.addActionListener()'), that listener will call another method (method2) when 'enter' key is pressed. If I do a 'mytextfield.getText()' in that method, the value I want to return is in the wrong method (method2 instead of method1).

I'm sure there is something simple I miss there, being new to object oriented programming. Thanks for any help.

EDIT: I guess I could store the value in a class wide variable. But I still don't see how method1 would know when to return that value since it won't know that method2 has gotten the value and stored it.

There's a lot of ways to accomplish this. I'm glad the dialogue works for you, but to help with the OOP:

You can indeed make it a class-wide variable. Then the subclass actionListener will have access to the class' variable, can set it, and then you just have to make method1 pull that variable.

How would method2 know when to return the value? I'd need to see your code, but can't method1 just call method2 when its finished calculating the value? Or can you simply do that logic in method1 itself, and have no method2 at all.

Alternatively, rather than defining a subclass action listener, you can make your main class an implements ActionListener and then define the methods for your main class, and merely pass mytextfield.addActionListener(this); Then its even more clear how method1 and method2 (since they're both just methods on your main class, now) can interact with each other and can access the same variables.

Maybe post your code on pastebin? These OOP principles are important, may as well learn em if you're learning java. :)

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Lazerbeam posted:

I've started java after learning python about a year ago, and I was wondering: what is there to gain by not using an IDE from the get go? I know I'll grab Eclipse eventually, what am I missing out on by not setting it up now?

Most of it is just convenient command shortcuts to speed up your dev time, combined with a good editor and syntax highlighting to again speed up your dev time.

But there's not much you can't do with notepad/vi and gcc/java/python command line. Its just, why not?

Plus, debugging is huge. I guess with python you can just use pdb on the command line too, but... ugh, that's ugly. You really want a nice IDE that lets you watch the instruction pointer move through the code, not just output on certain breakpoints. At that point you're not doing much more than writing asserts or print debugging.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

pigdog posted:

You'd almost never need to type a line of Java that starts with import. That's well a reason enough to use an IDE, if immediately pointing out syntax and other errors, smart autocomplete, smart refactoring tools, debugging and a thousand other things aren't a reason enough.

JavaDocs on mouseover / auto-complete / intellisense is pretty huge if you're new or working with a new API.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Lazerbeam posted:

Thanks, I'll take a look at Maven too.

As he said Maven is an absolute LIFE SAVER when it comes to dependencies. You do pretty much nothing except define which libraries you should in theory be using, and it takes care of everything else; it downloads the latest ones and links with them and compiles all at once.

It can be a little more complicated to set up, but its usually worth it afterwards. Also, if you have your own libraries, adding those to your dependencies and getting it mapped out can be a little confusing at first.

I disagree with Shaggar that you'd be a moron not to use it; Ant works great too and is easier to set up, and for simple projects or for people who are learning, just building through eclipse works fine (and is much simpler). That said: learn Maven whenever you can, on some projects it makes a world of difference. And once you've got Maven setup, there is 0 effort.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Jarl posted:

Yes, it is shallow copy under the hood, but that doesn't change that it shouldn't be necessary (if it was only an option it was another matter). In C++ STL you can iterate over keys, values and entries too, so that's not the explanation. It's not important but I'm genuinely curious why this was decided.

I don't know, honestly I think iterating through a key set is more intuitive than iterating through the map and calling first() or second() or whatever on each element to get the value you want.

Java came later and worries a little more about protecting you from yourself than C++ does. C++ lets you overload operators, java says "hey pal just make em methods". Not a huge difference. You lose a little syntactic sugar but you gain readability.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Crumpet posted:

Anyone got any clue why trying to bind to a port on a remote server (using a socket, obviously) would succeed when run as a standard java application, but fails when run under tomcat?

I've taken a look at network traffic both through my firewall and via wireshark, and I can see TCP requests heading out on the correct port and to the correct destination address, but all I end up with is a ConnectException under tomcat. This would be fine if it didn't work when not run under tomcat, and that I know the server is reachable under that port.

If it helps, I'm using OpenSMPP (here), and you can see how it's doing its binding here.

What do tomcat logs say? Are they receiving any requests? Is it actually running the application on tomcat?
Maybe a permissions issue, Tomcat might not even be running the program. Or it could be refusing the requests.

Check your tomcat configuration as well. Everything in /conf/, like server.xml and web.xml. I think you need to define a connector to the port you're using.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Crumpet posted:

Nothing in the tomcat logs other than the exceptions relating to this. Permissions are fine - I have full admin privileges on this machine, and I'm running tomcat from an elevated command prompt.

I've got a connector to the correct port in server.xml.

Oh, I see, Tomcat is trying to connect to the remote server, I figured that you were running the server on tomcat, rather than as an application.

Hmm, so Tomcat is the client. What about the server then, do you have access to its logs?

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Crumpet posted:

This was exactly it, thanks.

I knew it was permissions! :haw:

I've had so many cases where Tomcat doesn't start up properly when it should "just work", ugh.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

fletcher posted:

I haven't used it before, but the Play Framework seems like a good way to hit the ground running.

Play and other big frameworks like Spring are very popular, but they're also gigantic. From what I've seen they have a lot of dependencies and use a whole lot of their own way of thinking, so if you're going to subscribe to one of those, you're getting pretty deep into custom APIs and you're going to be married at the hip. Not that that's the end of the world.

But if you're just trying to learn some basic Java web stuff, I'd honestly start with just throwing together some JSPs. Then write some servlets to drop in Tomcat. Then maybe you wanna learn Play.

Hard NOP Life posted:

Agreed with everything you just said but I would recommend GlassFish over Tomcat for someone just starting out today. The concepts you learn will port over well to any of the other servers, butt the admin console is a lot easier to use and understand at first and don't require loving around with XML configs until you need to configure very advanced features. ALso there are plugins for it just like Tomcat in every IDE which will help with deploying your projects straight from the IDE.

I've used Tomcat and JBoss a lot more, but from what I've seen GlassFish is pretty dang cool, like you said the admin console is just simpler to use and more robust. They're all fine really.

Zaphod42 fucked around with this message at 22:37 on Nov 6, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

fletcher posted:

Yeah you're right, probably not the best way to start out. From what I had heard about it it kinda sounded like Django for Java.

Yeah its like Django or Rails for Java.

:barf:

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Woodsy Owl posted:

Good deal, thanks for those. I learned a lot reading through, and now I have some good bookmarks. It looks like the data structures already provided in the standard library throw exceptions that inherit RuntimeException, which makes them unchecked.

Yeah, exactly. Unchecked exceptions can be kinda confusing when you're learning exception handling for the first time. Runtime Exception for instance is supposed to be things that can't be predicted at compile-time, so its not worth making the compiler enforce them. Lots of time Runtime Exceptions mean things are so fubar you're just going to crash anyways and there's no real graceful way to handle it.

Also, (you probably already know this) you can always declare that your method throws the exceptions that the code it uses throws, and then it isn't responsible for having a try/catch block to handle those exceptions. Instead, if it gets an exception, it'll just pass it up the stack to the nearest calling method which DOES have a try/catch block to resolve the code. Lots of times this is actually the behavior you want. It depends upon what level of the code you're in and how intelligent / error correcting you want that code to be. So your Main function could call method A, which calls method B, and B throws an Exception. A doesn't try/catch it, it simply throws it up, so Main ends up catching the exception and prints out a handy error message to the user to let them know something went wrong (like their internet is disconnected).

Exceptions should be typed when possible, just saying catch(Exception e) all the time is bad practice.

Oh and don't ever loving write this:
code:
catch(Exception e){
}
Print the stack trace, print an error to system.out, do anything. But gobbling up exceptions without doing anything about them makes maintenance/debugging impossible. Better to just throw the exception than do this.
or this
code:
catch(Exception e){
    throw new Exception();
}
fuuuuuuck

Zaphod42 fucked around with this message at 21:11 on Nov 11, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

A Tartan Tory posted:

Another small question if I can get away with double posting this once. I'm now trying to make a dynamically generated table using SQL and java by doing the following.


However, I have a feeling my SQL is balls, because I keep getting exceptions when trying to use statistics.accessdata, pictures.ShortName, categories.ShortName from my container jcg. Can anyone give me an example of an SQL query that would work in this situation, to call up accessdata and the two different shortnames and then create a table displaying them ordered by the accesscount integer?

If your SQL has problems, then test it in SQL outside of any code first. Try executing that statement as is, by its lonesome, to prove the SQL isn't the problem or isolate it to that. (Plus then you get to see how the output is going to be formatted and double check that your code is going to receive what it expects) I don't have your database schema, but trying to execute that line of code gives me errors. Those errors tell you what you need to change.

What's going on here? Is jcg your database name, or is it a table? What's with all this 'statistics.accessdata' and 'pictures.shortname', are those supposed to be column names? I don't think those are valid. Are statistics and pictures themselves tables? Or are they supposed to be aliases? Or column names?

Your SQL syntax is way off, I don't even know what this is. :smith:

On the bright side, your code looks fine. I think your query is just fubar.

Zaphod42 fucked around with this message at 23:11 on Nov 14, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

A Tartan Tory posted:

jcg is Indeed my database that all of these tables are under, if that helps.

Yeah your SQL syntax is just like, entirely wrong. You don't reference the database name in a query, you're querying against a single database already. You can't query one database from another.

Go lookup SQL queries and read about the syntax for awhile, and make sure you really understand what a table and a column are.

SELECT <column>, <column> FROM <table> WHERE <condition> ORDER BY <condition>

Nowhere do you list <database> as part of the query. All of the columns, used in SELECT or WHERE or ORDER BY, MUST be listed as part of the FROM clause. (unless you do joins, which is more efficient, but more complicated syntax)

Periods should only be used for referencing table names or aliases, so SELECT a.name FROM person a would work, or otherwise without the alias you have to specify the full table name, SELECT person.name FROM person

Zaphod42 fucked around with this message at 23:48 on Nov 14, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Amarkov posted:

e: but I love teaching people basic SQL :(

Aw your answer was better than mine was. :smith:

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Looks good to me :thumbsup:

Your code before looked good so now that you've tested your SQL query against the database itself, plug that sucker in! You didn't hardcode anything so even if the number of columns was off it'd still work, which is nice, but in other situations you'd wanna double check the output you get from the database itself to make sure its giving you the right format of output for your code to parse.

Also sorry if we sound critical; its totally okay you're making mistakes since you're learning. And if we're posting in these threads, it means we want to help people, so you don't have to feel bad or anything.

Zaphod42 fucked around with this message at 01:01 on Nov 15, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

carry on then posted:

How big are these files? Do they have any line breaks or other delimiters anywhere? If they're reasonably small, you could probably get away with reading each file's contents into a string and calling fileString.indexOf("my string") to get the start of your string, then do a substring and convert to an integer. If you know there is a delimiter (so that your string and the number would be between two delimiters) you could go delimiter to delimiter to save memory. java.nio.Files in Java 7 can move the file pretty concisely, but you could probably get away with opening a stream to a new file in the destination directory, write everything out, then delete the source file, all of which can be done with java.io.File if you're stuck on Java 6.

You could just treat the string he's looking for as the delimeter, tokenize it based on that string, and then simply check the first 8 characters of each of the tokens.

Java code:
String input = "abunchoftextwhatever12345678andmoretextwhatever87654321";
String TARGET_STRING = "whatever";
StringTokenizer st = new StringTokenizer(str, TARGET_STRING);
while (st.hasMoreElements()) {
        try{
	    int value = Integer.parseInt(st.nextElement().subString(0,8));
        //if(value == something){ do something }
        }
        catch(Exception e){ System.out.println("NaN"); continue;}
}

Zaphod42 fucked around with this message at 17:41 on Nov 15, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Woodsy Owl posted:

Thanks for the confirmation. The 'why' was I wanted to see if I could use the idea of sending threads over sockets to implement some type of distributed computing. Turns out I can. And I agree it's super-inefficient and very insecure, but hey it works! Now I'm on to learning about something else...

That's fine, so long as you're aware that java has better and safer ways of accomplishing the same.

And remember, java only compiles to 'bytecode' (as .class files anyway, not speaking of JIT), not to machine code, so yeah it executes across JVMs. (mostly)

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Always brackets forever. :colbert: Whitespace is up to your personal preference.

Sedro posted:

Does anyone actually make that mistake? Insert a newline in any Java IDE and it will take you to the correct indentation.

Come join us in the Code Horror thread.

You better believe that poo poo happens.

The fact is you just don't want to have to trust the other guy when you could just do it the safe way.

Zaphod42 fucked around with this message at 06:38 on Dec 8, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Bullio posted:

I'm very new to coding, I hope I'm not wasting your time with such a low level question, but goons never let me down before.

Don't worry, we like the easy questions. They're easy to answer, and make us feel superior. :smuggo:

Bullio posted:

For class, I'm doing a simple little program where a user inputs information for 3 cats and the program outputs which cats listed are over 3 years and declawed. I finished it already and turned it in, but I'm looking for advice on a more elegant way to do it as opposed to the clutter I made grinding it out when I turned it in. We don't hit arrays until next semester and I couldn't figure out how to set up just one block of questions and apply the data to the correct object instance. So I made a set of System.out.println for each cat, which is ugly as hell. Anyway, using a for loop with a switch statement is the way to go, I think, but I keep getting problems in the implementation. Sorry if this is too low level.

Also, will this print out properly? i.e. "Enter the name of Cat 1:" "Enter the name of Cat 2:" etc

Sounds like you could organize some of this logic as a seperate method/function to call, which is something newbie programmers are usually very hesitant to do, but becoming comfortable with it is the real way to Getting It™ as a programmer. Rather than knock everything out in one method, build yourself some tools first, and then you can use those tools in a much simpler method.

That'll print out properly as you're expecting, however it'll print all of the "Enter:" blocks at once, and then go to your section which I guess would read the inputs? You may want to prompt separately for each one as you take the inputs.


Hah, I didn't know it had a wiki page, that's funny.

Gravity Pike posted:

In Comptuer Science we count starting at 0. In Java, we name classes starting with a capitol letter, in CamelCase, using full words.

Thing is he didn't make an off-by-1 error, so its not a big deal. So he's wasting a bit, in modern performance when you're learning that's trivial. I guess its good to know that you can count from zero, but really, that's minor. Making the off-by-one error is the real mistake, and he avoided that. It also prevents him from having to do i+1 on each loop iteration... so that's actually more efficient.

You should def get comfortable with camel case though, its a really good habit to get into.

variables and methods begin lower, then go capital. Classes begin capital. That way you can tell at a glance if something is a class or a feature of a class, and the capitols after the first make it much easier to read (since you aren't allowed spaces)

thisisreallyhardtoread

ThisIsPrettyEasyToRead

ClassName

methodName

variableName

Zaphod42 fucked around with this message at 23:52 on Dec 10, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Bullio posted:

If so, how do I get the boolean value assigned to it. I think I remember saying a boolean couldn't be set with a constructor. I could be wrong though.

boolean can't be constructed because it isn't an object, correct!

But Boolean is an object and can be!

You can then save that Boolean as a Boolean or as a boolean, because java has autoboxing (syntactic shorthand, the compiler will convert to wrapper classes and back automatically, since they're obvious)

Java code:
//plain data is not an object
boolean bData = false;
//wrapper class is an object
Boolean bObj = new Boolean();
//we can autobox a Boolean into a boolean
bData = new Boolean();
//or we can autobox a boolean into a Boolean
bObj = false;
//but you can't call new on a PDT (plain data type)
bData = new boolean(); //this is an error
bObj = new boolean(); //also error can't do either

Bullio posted:

Edit, nix the boolean question. You said there was a way to parse a string and pass the appropriate value to the boolean. Would that be a wrapper class?

The big B Boolean is a class which is a wrapper to little b basic data type boolean, yeah. And the parse method is a static method (you don't need a big B boolean instance to call it) that takes a String and returns a Boolean.

So there's a class in java like
Java code:
public class Boolean
{
private boolean value;

public Boolean(){ ... }
public Boolean(boolean b){...}
...
//something like this
private static boolean parse(String input){
   if(input.equals("True")){
   return true;
   }
   return false;
}
}
}
Boolean sure is a silly word. Boolean Boolean Boolean.

Zaphod42 fucked around with this message at 05:54 on Dec 11, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Bullio posted:

That's pretty awesome. Thank you. I guess I should download a version of linux and start fooling around with it as well then.

It can't hurt. Linux is fun because you can get the source code to most everything and build it yourself, so you can poke around and see how things are done, or make changes. Windows, everything is proprietary, you just flat out can't see the code ever to almost anything.

If you have a mac, OSX is totally POSIX so you can just learn on that instead of bothering with Linux. Its terminal is pretty good.

Alternatively you can install a linux shell in windows if you'd rather not deal with setting up partitions and a new OS. But it doesn't hurt to try a new OS, and some flavors of Linux like Ubuntu are really easy to set up compared to the old days.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Java code:
System.out.println(((Integer)foo).equals(bar));
At least that's always safe :) I just avoid == unless you're certain both are PDTs.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Woodsy Owl posted:

With regards to source control, would you want a separate repository for each sub-package? My projects are starting to intersect in that they end up using some classes that I've written prior. Is there a decent write-up detailing smart and effective package organization?

edit: Derp, http://docs.oracle.com/javase/tutorial/java/package/index.html

Nah that's way too many repositories and too much work. You probably just want one single repo, with seperate folders for each project, and code organized under project src folders based on package. If a package is used in a seperate project, you'll want to copy the source code to the new project folder so they're separate, or better yet, create a third project that has the common code and compiles to a library, and then copy that library to the other two projects after compilation and import it.

Maybe you have some branches for different release versions or something, but not per package, nahhh.

Projects should be able to pull from tons of different resources without any conflicts.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

hooah posted:

I'm trying to follow Stanford's Intro to Programming course to learn Java. However, there seems to be a problem with their distribution of Eclipse for Windows (here), or perhaps it just doesn't work well with Windows 8. When I try to run that, I get this hideous mess of errors that I don't understand. Could someone help me get this working?

I also tried using standard Eclipse, but couldn't get a Karel the Robot project working with it.

I don't have windows 8 so I don't know of its horrors, but you should be fine just using the normal Eclipse for Windows devs from the Eclipse page.

What was your problem with getting "Karel the Robot" to work with it? You're probably just not familiar with Eclipse, which I guess is why Stanford had a special build of Eclipse packaged ready to go. You'll just have to import the right project and make sure the build path is properly configured.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

hooah posted:

Using the standard version of Eclipse, I followed the directions here to set up Karel with Eclipse. However, likely due to my brand-newness at Java, I couldn't figure out how to translate the importing and class setup for the program written in the second lecture into something that would work with the directions I linked above.

That seems fine. If you've got the libraries imported, the 'second lecture program' you refer to should work. Namespaces are set up such that it shouldn't be machine specific.

So you're saying you've got the program that Stanford wants you to look at open in Eclipse, and Eclipse has the Karel external libraries imported.

So, whats the issue? You're getting a compilation error when you try to build the program?
Can you put the program on pastebin, or copy the output of the compiler error here for us? Need more information.

You may just have to make sure the library is imported for specifically that project. Alternatively Java's just complaining because your package name doesn't match the source folder or something, odds are you can just mouse over the red underline and Eclipse will suggest a fix for you. (Package name X should be Y, for example) Click the underlined text and it'll apply the fix automatically.

Zaphod42 fucked around with this message at 19:51 on Dec 18, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

hooah posted:

That helps conceptually, but not really specifically, since evidently the Karel distribution I grabbed isn't quite the same as the one used in the Stanford lectures, so I don't know which class I should be extending. Hmm.

As an aside, do you need the this. in a method, or can you leave the data member naked as in C++?

Here's a page I found on Karel for java

http://programmingjava.net/2-basic-karel-program/

http://programmingjava.net/3-improve-karel-using-methods/

Looks like that's the same library you're using? Yeah, if the Stanford library is named differently than yours then the extends won't work. Unfortunately that means the rest of the API might be different too, so you may want to go back and try to find a better stanford karel library and get that working. Although... this page here references Stanford. Hmm. Maybe they are the same.

You generally don't need to use "this." in a method, class field variables have full class scope. However, if you have a variable with a name like myVar, and then in a method you declare "int myVar = 10;" you're going to now have no way to refer to the class level variable myVar, since they're the same name. This is called shadowing, and the way you can get around it is by saying "this.myVar". The other case where you need this. is if you're passing yourself as a reference ( myMethod(this); ) or some other special cases. It isn't usually needed, no.

Looks like this should work

Java code:
import stanford.karel.*;
public class MyKarel extends Karel {
    public void run() {
        move();
        putBeeper();
        move();
    }
}

Zaphod42 fucked around with this message at 17:00 on Dec 19, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

hooah posted:

I'm not sure if it's the same library. The one I got was from Pace University; the link from that Java tutorial is dead. The first thing I tried doing while watching the lecture video was saying import standford.karel.*;, and Eclipse couldn't resolve the stanford import. I used the contact link on the Stanford site to ask if there's somewhere to download the Karel project or if they could make heads or tails of the error their Eclipse distro was giving me, but based on their automated response, I'm not hopeful.

I'm confused. You said you were doing Stanford's intro to programming course. Stanford sent you to Pace?

You can't use somebody else's library without some kinda documentation. If the links are dead then don't use that. What are you doing this for anyways? Trying to learn java? There's infinity tutorials out there, pick a new one that's better documented and better maintained. Trying to follow along with a different library probably won't work well, especially if you're new. You'll just keep getting bogged down and lost.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
^^^^ Listen to this man.

greenchair posted:

What I'd really like to be able to do is something like:
ArrayList<? extends Dog, implements Guard, Animal> (Then I could fill in the list with GermanShepard, PitBull (Sub Classes of Dog) types etc.
Does that make sense? Is there any way to do it?

I think you're making it way harder than it needs to be.

How familiar with OOP, inheritance, and generics are you?

Why not just create new interface SubDog extends Dog implements Guard, Animal, then all your objects extend SubDog.

ArrayList<SubDog>

Although logically Dog would implement Guard, Animal or... yeah probably reorganize your class hierarchy.

Adbot
ADBOT LOVES YOU

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

greenchair posted:

Thanks that's really helpful! Are there any languages that would support the "mTF()" type thing? I was thinking that the reason It'd be useful is that the Male and Female subclasses would have different methods, or perhaps different implementations of an abstract superclass method.

See Static vs Dynamic typing, such as Duck Typing.

http://en.wikipedia.org/wiki/Type_system

http://en.wikipedia.org/wiki/Duck_typing

TL;DR: Yes.

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