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
ynef
Jun 12, 2002

fret logic posted:

Thanks for the advice, the bit about making a more robust Player object is very helpful. I spent a long time thinking about how to set that up and this clears it up for me :)

This short program was a quick attempt at displaying some information based on user selection using a setup kind of like I would if I was making the actual game. I will be making the game at some point as a larger project, but at the moment I'm just making random pieces to have something to do.

Depending on your game and what it will support in the future, I'd say that Player should be an abstract class and that you should subclass it with a Fighter and an Archer class. The reason (which may not be valid in your case) is that, for instance, you'll want to give all archers a bonus for ranged weapons or restrict so that fighters can't used crossbows (whatever). If you stick to using conditional statements (if, switch) then you will quickly get a headache trying to code all these rules that will be easily avoided if you just go with the subclassing. Also, the constructor for each class will be very simple and you can still keep the toString() method (which you should use) in the abstract Player class. Adding more types of Player will be ridiculously easy too.

If you go that route, keep in mind that you need to change all attributes in Player to "protected" for subclasses to access them.

Adbot
ADBOT LOVES YOU

ynef
Jun 12, 2002
Row 16 in the file that the JVM complains about says: "Graphics2D g = (Graphics2D) drawSpace.getGraphics();" -- at that point, however, drawSpace is not initialized to anything and is therefore null.

ynef
Jun 12, 2002

fletcher posted:

I'm looking to implement some charts on a Java web application. Right now I'm reading about JFreeChart. What are some others worth looking into? I'd prefer to go down either the static images route or possibly flash based for some user interaction, no applet type stuff.

Tow questions: what kind of charts, and can you run other programs on your server as well? Such as, for instance, gnuplot? Just asking. Also, since it's web, I'm guessing you want to output at least PNG or something (perhaps have support for PDF and PostScript as well)? More specs, please. :)

ynef
Jun 12, 2002

PianoDragn posted:

* IMPORTANT: Performance is very important, please make the method efficient *

I am making an app right now and could use the following Graphics2D wrapper methods (I don't know a thing about Graphics2D)

1.) I want a method called applyOpacity(Image,Double) where it accepts an Image type and a double specifying the opacity. It will then use Graphics2D to apply the opacity to the Image and return the new Image. I don't know if this is possible or not, if it can't be stored in an image and instead needs to be stored in a Graphics object then return that instead.

2.) applyLighting(Image,Int) I send it an image with a brightness 0 being completely black and 100 being completely white? It then returns the resulting Image.

The useage would be if I wanted to bring something ot the foreground I would draw my background on offscreen image, pass it to the lighting method and darken it. Then I would take my 2nd image thats foreground send it to opacity and drawImage onto the offscreen image.

Thanks!

Read up on VolatileImage, it is supposedly faster and stored in video RAM (according to this). Perhaps that could speed things up for you?

ynef
Jun 12, 2002

Emo.fm posted:

What's the deal with loading images from the web to display in applets? I'm following the directions from this site, but whenever I try to compile, I'm told that the method "getImage()" doesn't exist.

I'm doing this within a file that is a smaller class used in the Applet, not the Applet class itself, so could that be the problem? Pretty much the entire program is finished except for this (I was previously working offline as an application, and therefore just using a toolKit) so I'm not willing to move the loading of graphics into the Applet class, unless that's the only way. Ideas?

(Just for clarification, here is exactly how I'm trying to implement this:
code:
 Image myImage = getImage("http://www.website.com/image.gif"); 

You answered your own question, there. Your code attempts to call a method called getImage() in your small class that is used in the Applet class. If you haven't written a method like that, then it is not going to work. Call the Applet class' getImage() method instead.

ynef
Jun 12, 2002

Emo.fm posted:

PS - If what you meant was to call Image myImage = MyApplet.getImage("url"); that doesn't seem to work either.

No, that doesn't work because getImage() is not a static method. Do you have a reference to an object of MyApplet? If so, you should be able to call the method that way. Either way, I think you should review your textbook again concerning references and method calls.

ynef
Jun 12, 2002

shodanjr_gr posted:

If i go to the command prompt and do a "foo.jpg", the image will open in the default program that ive selected to handle that kind of file. I dont have to use the filename as an argument while running the program...(which seems pretty reasonable, since it would make any sort of search application impossible to develop - which is what i am making).

That's what i want to accomplish. But in java.

At least in previous versions of Windows, you had the "start" command. I don't run Windows, so I wouldn't be able to check if this is still the case. "start filename.something" would be equivalent to double clicking the file in Explorer. This works (worked?) for folders also. So, all you'd have to do is find out the file name and send that as the argument to "start", and you're done. My guess would be that "filename.something" is simply interpreted as "start filename.something" by the cmd shell.

Why is something this Windows-centric developed in Java, though? :)

ynef
Jun 12, 2002

drunkill posted:

code:
public class Exercise1
{
	public static void main(String[] args)
	{
	 Scanner scan = new scanner(System.in);
	 System.out.println("Please enter your first name:");
	 first = scan.nextInt();
	 
	 System.out.println("Please enter your surname:");
	 last = scan.nextInt();
	 
	 System.out.println("Please enter the year you were born:");
	 int age = scan.nextInt();
	 
	 System.out.println("Please enter your height:");
	 height = scan.nextInt();
	 
	 System.out.println("Please enter your gender");
	 gender = scan.nextInt();
	 
	 System.out.println("Do you hold a drivers license?");
	 last = scan.nextInt();
	
	
	 System.out.println("Hello "+ first + last, "you're" + age "years old this year.");
	 System.out.println("You are " + height "meters tall, have a gender of" + gender "and it is" "that you can drive.");
	}
}

This code shouldn't compile. You're missing data types in front of your variables, and you also have a problem with missing + signs in that last System.out.println() row. You need to put it between things that should be glued together (concatenated would be the correct term) to form a new string.

The thing about data types as someone mentioned, think of them in database terms since you're comfortable with databases. You wouldn't declare that a column should include integer numbers if you're going to store names in there in a database. Same thing with Java -- figure out the correct type, then store data in there.

Good luck, you'll do this stuff easily within a matter of days!

ynef
Jun 12, 2002

Startacus posted:

Edit: Another thing, is there a good way to write nodes to files, like from a binary tree?

The topic you want to Google for is called Serialization. Preferably, serialization to XML. Like someone else said, this sounds like homework, so I'm just going to point you in the right direction.

ynef
Jun 12, 2002

Sarah Sherman posted:

I'm playing around and messing with some programming homework and I'm getting a little stumped on this. This program basically uses a linked list and lets the user write a polynomial, input a number to be evaluated, and then returns the answer. So far I have all the math working, except I can't figure out a solution to print out the user's polynomial. Here is my code:
Polynomial.java
Node.java
As you can see, It is outputting each the polynomial node after the input, and it just prints the same node each time. What is the best way to go about this? Also, for some reason it doesn't print out the first inputs, and starts printing them after you input the second numbers. Why is it doing that? any help would be appreciated.

You will be really annoyed when you find out the answer.

From where are you getting the values you are printing?

ynef
Jun 12, 2002

Jmcrofts posted:

I'm really new to Java, and am learning it for a CS class. I installed the Java SDK on my home computer, and whenever I try to run my compiled code through the command prompt I get an error message that says
"Exception in thread "main" java.lang.NoClassDefFoundError"

I looked this up and tried some solutions about editing my CLASSPATH in system settings, but I still haven't been able to get it work. Any help would be much appreciated!

What you're probably doing is that you type "java MyClass.class", when you should type "java MyClass" (without the ".class" suffix). This of course assumes that you follow your tutorial precisely and have a method like "public static void main(String[] args)", which you may consider the "entry point" of a program.

ynef
Jun 12, 2002
Excellent post, 1337JiveTurkey!

It should also be noted that there is a nasty consequence to letting just this one thread handle all the events in Swing: if your event handling includes a lengthy operation (say, getting a file from a network location or calculating something that takes a while), that means that you have effectively prohibited the GUI from being responsive during that time. To avoid this problem, you must perform lengthy tasks in the background using another thread. Thankfully, there is a class for making this easy, called SwingWorker.

Read up on Concurrency in Swing, and really get comfortable with the concepts presented there. Obeying the rules there is crucial to making usable programs.

ynef
Jun 12, 2002

Lord Wexia posted:

So my question is, how should I think about this double quote character and can my space-character oriented method still work? Or am I going to have to re-write this?

I don't mean for this to be a "help me with my homework" post but if anyone has any tips on where I should move from here, I'd really appreciate it.

I'm going to assume that you have to do all this stuff on your own and not just rely on some smart other tool or library. Your space-based approach may be rewritten to handle this case as well.

There are at least two solutions. One which is more simple but specific to your current problem, and one which is more general. A really simple, but hard to modify and adapt solution would be as follows: simply keep track of whether you are within quotes or not using a Boolean variable. If you are, then all characters you read (until you encounter the closing "-character) should be appended to your current partial result. If you are not within quotes, then continue like you have before with your space-based parser.

A nicer approach would look as follows in pseudo code.

code:
String readUntil(Datasource source, Character[] stopCharacters) {
  String result = ""
  done = false
  while (!done and source.hasNext()) {
    Character c = source.nextCharacter()
    if (c in stopCharacters) {
      done = true
    } else {
      result.append(c)
    }
  }
  return result
}
Then just change what the array of stopCharacter contains based on context (within quotes or not). Keep calling the method until the data source is depleted, and store the strings it gives you somewhere (like in a List<String>, I suppose).

If you would implement the second solution, you obviously need to perform more error checking and stuff. In particular, you might want to throw the empty string away. ;)

ynef fucked around with this message at 18:15 on Feb 11, 2009

ynef
Jun 12, 2002

Captain Pike posted:

I am very new to Java, and I am attempting to compile a project found on Source Forge:https://sourceforge.net/projects/opensmus/

Problem: The source code I downloaded seems to require third-party classes/libraries. I know this due to compile errors. I am downloading classes one by one, as the compiler complains. Some of the packages I download then complain about other required third party packages. I have no idea if I will have to download hundreds of packages.

This seems horribly inefficient. Is there a way to get a list of all required packages, perhaps via Netbeans or other IDE?

Example third-party packages: javax, junit, hamcrest.

Absolutely. Check out Maven.

[edit] Maven requires that there is a Maven-specific file, but serious projects use it. If this one doesn't, suggest it!

ynef fucked around with this message at 07:38 on Feb 19, 2009

ynef
Jun 12, 2002

Flamadiddle posted:

So I'm trying to make a bouncing ball simulator. I've managed to make a model but want to represent it graphically. So far I've got the model in one class and the GUI in another. Couple of questions:

1 - To make the physics work I've used Thread.sleep() in a while loop to allow for time-dependent functions. Is this anywhere near the best method? I get the feeling it's not because....

2 - I can't figure out how to pass a real-time height parameter from the bouncing ball procedure to the GUI to represent it.

Any pointers on how this would best be implemented would be appreciated.

This approach can work. There are alternatives, but let's first study the one you have.

In your current approach, you would have one thread that runs the model, and then you'd have another that manages the GUI. When the GUI thread decides it needs to redraw the scene, it should query the position of the ball from your ball model object (create the ball model object first, then feed the GUI object with a reference to it). However, since you have two threads working with the same data (the position of the ball), you should make sure that your inter-thread concurrency is handled well. Read up on thread concurrency in general, and on the "synchronized" keyword especially.

Another approach is to have only one thread, the GUI thread. The pseudo code for it would be:

code:
while still running:
  startTime = get current time in milliseconds
  ballModel.update(startTime - stopTime)
  // update other stuff
  stopTime = get current time in milliseconds

  // sleep appropriate time to get reasonable FPS, using startTime and stopTime
With this approach, the ball model is fed information about how long ago it was since it was last updated, and can proceed with the simulation accordingly.

Since you already have a working ball simulator, I would suggest that you stick with the first approach, the second one being only for future reference. The more easily you can make use of several threads these days, the better. ;)

[edit] If you want to study this topic further, the phrase to search for is "game loop".

ynef fucked around with this message at 06:25 on Apr 14, 2009

ynef
Jun 12, 2002

StickFigs posted:

The only problem is I still don't understand the for-each loop, I found this page which explains it but I still don't understand exactly what is going on, especially where it says the first example should be read as “for each TimerTask t in c.”

Say that you have some collection of values: a list, an array, a hash set... any collection (that implements the interface Iterable<T>). It is very common to iterate over every element in this collection and do something with each element. Previously, we had to write code like this:

code:
for (int i=0; i<someArray.length; i++) {
  // do stuff to someArray[i]
}
But see, that's what the code looks like for an array. If you want to iterate over a list, you had to write:

code:
for (int i=0; i<someList.size(); i++) {
  // do stuff to someList.get(i)
}
...and there were other variations for various other data structures that all had in common that they held a bunch of values, and we would like to iterate over these values in sequence. Stupid, right?

So now we have a new type of for-loop that does just what we want: it allows us to write code that looks the same no matter which underlying data structure is used, because it solves the same basic problem. It basically says: iterate over the entire collection, and give me a reference to the current element so I can do something with it. It looks as follows:

code:
for (ElementType currentElement : collectionOfElements) {
  // do stuff to currentElement
}
where "ElementType" is the type of elements stored in collectionOfElements (such as String, or Integer). Not only does this give us a bit cleaner code (no indexes all over the place), but it also means that we can easily switch what kind of collection we're using to store these elements without breaking our for-loops (recall the difference between the array and list iterator loops above). And because all that is required from a data structure to be used in this way is that it implements a certain interface, Iterable<T>, you can make your own data structures compatible with this clever type of loop.

ynef
Jun 12, 2002

fge posted:

I'm having problems with servlets in Ubuntu. I'm trying to add the servlet-api.jar file from Tomcat to Java, so I added this line:
code:
CLASSPATH="/Desktop/apache-tomcat-6.0.18/lib/servlet-api.jar:."
to etc/environment and restarted. But when I try to javac my file, I still get error messages saying that javax.servlet and the like don't exist. What did I do wrong?

1. You need to write "export" first on that line.
2. That folder name is wrong: your desktop is at "/home/yourUserName/Desktop/".
3. And you don't want to replace your classpath like that (you should probably just append to it, like so: export CLASSPATH="$CLASSPATH:/more/stuff/here:/even/more/stuff").

Also, don't put stuff like this in /etc/environment. Put it in your ~/.bashrc, or make a script that exports such variables for you that you run as a setup before running javac/java.

ynef
Jun 12, 2002

UR MR GAY posted:

I'm using the scanner class with a line separator as the delimiter to parse an obj file. The scanner won't detect any line separators until i manually open the file in WordPad and add just one. So my question is, how can I circumvent that?

Can you explain what you are trying to do (there may be a better way) and also posting a sample OBJ file that you are working with?

A possible cause of the problem could be related to Windows and UNIX treating line separators differently, but I think Scanner is smart enough to handle such things on its own.

ynef
Jun 12, 2002
Before learning Swing, it might be good for you to learn more about multithreaded (programs that do more than one thing at a time) programming. Not only is it really cool stuff, but you have to know it to make Swing programs. No exception, you need to know threads to do GUI programming.

ynef
Jun 12, 2002

almostkorean posted:

Yes, but I'm getting the same issue if I'm trying to run something that's not in a package

Edit: nevermind, java -cp . Blah works on something that's not in a package, how do I run something that's in a package?

You have to be at the top level directory, and then specify the Java class you want to run with the whole package information preserved. An example:

Say you have the following directory structure for your project:

code:
src/
src/com/somethingawful/forums/SomeCode.java
src/com/somethingawful/forums/SomeCode.class
lib/
res/
Now, src holds the source code. The SomeCode class is defined as being in the package "com.somethingawful.forums" (hence the directory structure). To run, you'd go to the "src/" folder and write "java -cp . com.somethingawful.forums.SomeCode"

ynef
Jun 12, 2002

FateFree posted:

In math terms, how do I find the smallest power of 2 thats greater than a given number, in fast java code?

In math, you'd probably get away with ceil(log2(given_number)), but Java doesn't have a general logarithm function like that (just the natural logarithm). You'd have to use the Change of Base theorem to compensate.

ynef
Jun 12, 2002

Flamadiddle posted:

Okay, I have no idea what's going on but I'm all of a sudden having real difficulty with packages and classpaths under Windows 7.

I've just tested the following:
code:
package mypack;
public class a{

     public a(){
	  System.out.println("found me");
     }
	
}
and class b:

code:
package mypack;
public class b{

     public static void main(String[] args){
         a mya = new a();
     }

}
I'd expect b to run, find a in its package and construct it, but I get cannot find symbol errors. It works if b is outside the package and imports a, but not this way. This is really bugging me and I can't figure it out. Any suggestions?

Edit: It seems to be a problem with the way I was compiling. if I specify the classpath as .. when I compile within the mypack folder it compiles fine. I must have the classpath set differently on my other pc, I guess.
Nope, that's what is supposed to happen: the class path should point to a location where the subdirectories are the same as the package names of the classes that you want to use.

ynef
Jun 12, 2002

Kaltag posted:

Whats the best way to make java do something every 3 hours then do nothing in between?

code:
while(true)
{
   Thread.sleep(3*60*60*1000);
   doSomething();
}
Seems too easy to be true. Of course I would add some code to make sure that the time that doSomething() took to run is counted, but this gets the basic idea across.
Well, you can always over-engineer it by using a ScheduledExecutorService if you want, but what you had should work too.

ynef
Jun 12, 2002

Aleksei Vasiliev posted:

Yeah, either save every line of what your client is POSTing and what is returned, or somehow run a packet logger.

Oh, and try replacing the "/"s in __VIEWSTATE with "%2F" instead. Maybe for __EVENTVALIDATION too.

tcpmon is quite good for this. You start it up, tell it to act as a proxy, it prints out both request and response. Simple and just what is most likely needed here.

ynef
Jun 12, 2002

GravyWPG posted:

I ask the teachers about it and they tell me to install version 6. I do that, reinstall Greenfoot, reboot, and it STILL DOESN'T loving WORK. I'm missing assignments because of this loving poo poo.

Can anyone help me with this poo poo? My marks depend on it.

Thanks in advance.
Since your grade depends on it, for now just get the portable version. It is self-contained and includes a JDK environment that the Greenfoot guys have tested and obviously ensure that works.

Choose the stand-alone version here:

http://www.greenfoot.org/download

Once that is done, try to fix things so you have your "real" Java environment up and running, but just take the packaged version first.

ynef
Jun 12, 2002

Hot Yellow KoolAid posted:

I'm having a problem with an intro java GUI assignment. I'm supposed to implement a mock radar display (similar to marine sonar) with a sweeping arm that spins every second. (The display shows other things, but I think I have those objects figured out). My attempts to implement the sweeping arm have been based off taking the java code for an analog clock's second hand and making it move 60X faster.

This is where I'm stuck. I'm using Graphics2D for GUI, and this is the code I have so far:
http://pastebin.com/xdU0aZMk

...and here is where I got the code for the analog clock:
http://javacodespot.blogspot.com/2010/05/java-analog-clock.html

Is implementing the swing-arm this way a lost cause? Some of the other analog clock/mock radar applications out there work by extending the Applet class instead of the Frame class (like I do), and I was wondering if that would be a better option.
Have you covered threads yet? I think the idea is to schedule a thread that fires a couple of times per second, draws the radar arm in a new position (if you have a counter for the angle, increase it and then take the value modulo 360 to figure out where it should point this time), and then puts airplane dots at the correct positions.

Are the planes supposed to move as well?

Post a link to the actual assignment, please.

Hot Yellow KoolAid posted:

Also, I need to implement grid lines in this somehow. Is there any way to draw lines using Graphics2D? I'm pretty sure I could solve this problem just by drawing some really slim rectangles.
You have code in the file you pasted that draws lines, dude.

Adbot
ADBOT LOVES YOU

ynef
Jun 12, 2002

404notfound posted:

One more thing you can do to clean up the code. I'm assuming you fixed the code by asking for input both before the while loop and also within the loop at the end. While this works, duplicating code is generally frowned upon.
I'd even go as far as suggesting making the if statements have blocks (just to avoid the classical bug where you add another indented statement and don't realize that it will always execute since the compiler does not regard it as having any relation to the if-statement) and changing the System.exit() error code from 1 to 0, since typing a negative number is the "normal" (as in non-erroneous) way of exiting this program. You know, if this will be graded by someone at some point.

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