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
narbsy
Jun 2, 2007

Newf posted:

Well I've done that and it works, but I'm completely confused. Isn't the "thing" that you put in theses <> doodads the 'type' of object that the arraylist will store/retrieve?

aren't 'double's a thing in java, while 'Double's aren't a thing?

Anyway thanks :)


If I wanted an ArrayList of integers, would it be ArrayList<Integer> or ...?

There's a difference between the primitive type double and the Object type Double. These object types exist for all of the primitives, as you must use an object type in generics and not primitives.

Java will "auto-box" these for you so that you can treat them essentially the same. You should probably look that up for some more information on how they differ.

Adbot
ADBOT LOVES YOU

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Jeez, be more helpful guys.

Thanks both.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

brosmike posted:

code:
myIntList.add(new Integer(1)); // This works but it looks unpleasant
use Integer.valueOf(1) or autoboxing, don't ever use new for Integer, Boolean, etc.

Boxing uses valueOf or equivalent.


Keep in mind that boxing/unboxing does take time. So adding thousands of ints to an Integer list will be slower than using arrays.

Thermopyle
Jul 1, 2003

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

The past page or two has made me remember how much I wish I was developing with Python right now.

brosmike
Jun 26, 2009

Aleksei Vasiliev posted:

use Integer.valueOf(1) or autoboxing, don't ever use new for Integer, Boolean, etc.

Whoops, my bad - this is absolutely correct, listen to this guy.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
The fun part of autoboxing is that it caches "frequently-used" values, which lets you do something like this:

code:
Field iv = Integer.getClass().getDeclaredField("value");
iv.setAccessible(true);
iv.setInt(Integer.valueOf(1), 500);
Which is guaranteed to piss off anyone else who has to maintain your code.

poemdexter
Feb 18, 2005

Hooray Indie Games!

College Slice

Blacknose posted:

I need a good Spring MVC book. Any ideas?

This got skipped over, but I recommend:

http://www.amazon.com/Spring-Action-Craig-Walls/dp/1935182358/ref=sr_1_1?s=books&ie=UTF8&qid=1311350259&sr=1-1

I have the second ed. The third just dropped last month I think.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I was laying on the floor just now thinking about the line of text that I'd been instructed to enter at the beginning of every program:

public static void main(String[] args)

THIS IS BECAUSE the main method (is the method that runs without getting called?) (potentially) takes any number of string arguments, which are in fact (this is my guess) command line arguments?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Newf: You are correct. If you launch your program 'Foo' like:
code:
java Foo blarg quux
The args array will contain:
code:
{"blarg", "quux"}
Additionally, the main() entrypoint is:

  • public, because it must be accessible outside the scope of the enclosing class, from any package.

  • void, because it does not return a value. If you want to provide a C-style return value to the operating system when your program completes, use System.exit(), which takes an int return value.

  • static, so that it is not necessary to instantiate an instance of the enclosing class to call the method. Another way of thinking of this is that the entrypoint of a program is a property of a class, rather than a property of an object.

This may have helped, or it may have made you more confused.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Internet Janitor posted:

This may have helped, or it may have made you more confused.

A little of both. Thanks very much :)

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
OK, so more trouble from the resident java noob.

I'm trying to make a program that uses scanner to take a positive integer as keyboard input, but instead of crashing at faulty input (like a string, for example) it asks for the input again.

When I run the following:

code:
import java.util.Scanner;
public class Temp{
	public static void main(String[] biff){
		Scanner input = new Scanner(System.in);
		int i = input.nextInt();
	}
}
with input "fred", this gets shot back at me:

code:
fred
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:840)
	at java.util.Scanner.next(Scanner.java:1461)
	at java.util.Scanner.nextInt(Scanner.java:2091)
	at java.util.Scanner.nextInt(Scanner.java:2050)
	at Temp.main(Temp.java:5)

Process completed.
So I figured I could use the nextInt() method in a try block with a catch (InputMismatchException x) block to deal with non-integer inputs. But when I complie this:

code:
Scanner uInput = new Scanner(System.in);
int temp = 0;
while (temp <= 0){
	System.out.print("How many students are there? ");
	try{
		temp = uInput.nextInt();
		if (temp <= 0)
			System.out.println("Please enter a positive number!");
	} catch (InputMismatchException x){    // compile error here
		System.out.println("Please enter a positive number!");
	}
}
I get "cannot find symbol class InputMismatchException" as a compile error. It's probably obvious to you now that I don't know how to work exceptions at all, but what do I do to make this work?

JingleBells
Jan 7, 2007

Oh what fun it is to see the Harriers win away!

Newf posted:

OK, so more trouble from the resident java noob.

...

I get "cannot find symbol class InputMismatchException" as a compile error. It's probably obvious to you now that I don't know how to work exceptions at all, but what do I do to make this work?


Have you got an import for java.util.InputMismatchException ? It's not in the java.lang package :)

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
import java.util.InputMismatchException;

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I certainly haven't, but wouldn't it be covered by importing java.util.Scanner? How else would the first example program there have thrown the error?

e: well this seems unanimous, and thank yous, it worked, but my-oh-my I have no idea how java works at all.

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
Scanner has its own imports in its source. Importing a class that imports something else doesn't import its imports.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Import statements are not necessary to use a class- they are what allow you to use a short name when referring to classes rather than the fully qualified name. Your previous program would've compiled fine if you'd used the fully qualified name java.util.InputMismatchException instead of just InputMismatchException.

gonadic io
Feb 16, 2011

>>=
Ok, so I've gotten myself really confused over how dependencies work in Java - am I correct in thinking that "import org.apache.xxx" gives you absolutely no clue which .jar file actually contains the class you want? I have 15-20 .jar files, is there any way to search through which ones contain which classes easily?

Also, I have a project in eclipse that was made when nested packages were a thing, which they're now not. I am completely lost on how to make the dependencies work - there are 15-20 packages inside a single Java project in eclipse and they all depend on each other - how do I satisfy the imports? At the moment, they can't see each other.

One last thing - does eclipse have a feature where it'll automatically look inside say /usr/share/java for dependencies so that you don't have to add the external jars manually?

I've been banging my head on this problem for a while now and I do so hate outdated documentation. Is a possible workaround to go back to an older version of eclipse that does have this nested modules feature?

ivantod
Mar 27, 2010

Mahalo, fuckers.

AlsoD posted:

Ok, so I've gotten myself really confused over how dependencies work in Java - am I correct in thinking that "import org.apache.xxx" gives you absolutely no clue which .jar file actually contains the class you want? I have 15-20 .jar files, is there any way to search through which ones contain which classes easily?

Other than package itself having a name similar to the name of JAR file itself, no, it doesn't give you any kind of clue. As long as the JAR is included in the classpath, the class will normally be found by gthe JVM, regardless of which JAR it physically resides in (so in theory you could pack everything in one big JAR file and it will still work--I am NOT recommending this of course).

I am not aware that Eclipse has any functionality to search arbitrary JAR files for classes--however, if the jar files are included as build path of one of the projects in the workspace, the Ctrl+Shift+T should be able to find where a particular class is based on its name.

There are also tools which can search a whole directory of JARs for a particular package/class, such as this one.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I don't think I know how to use BufferedReader.

code:
// method which creates a bufferedreader only if it finds the file
// referenced by the user
	public static BufferedReader mkReader(){
		Scanner input = new Scanner(System.in);
		System.out.print("What is the name of the input file? ");
		try{
			return new BufferedReader(new FileReader(input.next()));
		} catch (Exception x){
			System.out.println("File not found!");
			return mkReader();
		}
	}
This is a method in the main class, to be called in the main method. I think maybe it won't work because the main method is outside the scope of the FileReader created in the class? Is this right? Can I rewrite the method to return both the FileReader and the BufferedReader?

ivantod
Mar 27, 2010

Mahalo, fuckers.

Newf posted:

I don't think I know how to use BufferedReader.

code:
// method which creates a bufferedreader only if it finds the file
// referenced by the user
	public static BufferedReader mkReader(){
		Scanner input = new Scanner(System.in);
		System.out.print("What is the name of the input file? ");
		try{
			return new BufferedReader(new FileReader(input.next()));
		} catch (Exception x){
			System.out.println("File not found!");
			return mkReader();
		}
	}
This is a method in the main class, to be called in the main method. I think maybe it won't work because the main method is outside the scope of the FileReader created in the class? Is this right? Can I rewrite the method to return both the FileReader and the BufferedReader?

First of all, I think that calling the method recursively in case of exception is probably not the best idea.

Second, when you say 'not work', what do you mean? This code will for sure not work for any file names that contain spaces since Scanner.next() will normally give you part of input until the next whitespace character every time it's called, until it consumes the entire input. You can use input.nextLine() to get the whole line of input (not including the line separator character).

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Newf posted:

I don't think I know how to use BufferedReader.

code:
// method which creates a bufferedreader only if it finds the file
// referenced by the user
	public static BufferedReader mkReader(){
		Scanner input = new Scanner(System.in);
		System.out.print("What is the name of the input file? ");
		try{
			return new BufferedReader(new FileReader(input.next()));
		} catch (Exception x){
			System.out.println("File not found!");
			return mkReader();
		}
	}
This is a method in the main class, to be called in the main method. I think maybe it won't work because the main method is outside the scope of the FileReader created in the class? Is this right? Can I rewrite the method to return both the FileReader and the BufferedReader?

I'd do something like this for the body of the method:

code:
Scanner input = new Scanner(System.in);  
System.out.print("What is the name of the input file? ");
while (true)
{ 
     File file = new File(input.nextLine());
     if (!file.isFile())
     {
          System.out.println("That is not a valid file path, please enter another:");
     }
     else
     {
        return new BufferedReader(new FileReader(file));
     }
}
You might still want to try/catch in case of other errors, but I'd recommend not to rely on exceptions for something you expect to happen on a regular basis.

edit: Although I don't immediately see any reason why your original method won't work. What's the error?

ShardPhoenix fucked around with this message at 07:37 on Jul 25, 2011

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I eventually got my original code to work. The problem was that in my main method header I didn't have "throws IOException". I have no idea what that does or why it needs to be there.

Why would it be a bad idea for a method like that to call itself recursively? It just works until it's been given a legitimate input file.

zeekner
Jul 14, 2007

Newf posted:

I eventually got my original code to work. The problem was that in my main method header I didn't have "throws IOException". I have no idea what that does or why it needs to be there.

Why would it be a bad idea for a method like that to call itself recursively? It just works until it's been given a legitimate input file.

You probably know what an exception is, since you used a try/catch block earlier. When you throw an exception, it will send that exception to whatever called that function. For example, inside the BufferedReader class, if it runs into an Input/Output error, it will throw an IOException. This passes that exception up to your function, and now you need to deal with it.

Now, when you call a function that can potentially throw an IOException, you have to either put that call inside a try/catch or throw it again yourself. By throwing the error, you are essentially passing it up the line. If you throw the exception while in your main() function, the system will catch the error, kill the program, and print an error message.

Recursively functions are bad in your specific case. Imagine that the function failed, your catch block will try again. There is no reason to expect it to work the second time, since nothing has really changed. It will fail again, and call that function again ad infinitum. Eventually it'll crash from out-of-memory or something. e: Misread the recursive bit. It'll technically work the way you wrote, but it's better to use a while-loop or something, instead of recursively calling the function.

zeekner fucked around with this message at 18:10 on Jul 25, 2011

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
The "throws" clause tells methods calling that method that somewhere in your method, an exception of that type may be thrown. Those methods should either catch that exception of throw it themselves so another method would have to handle it.

It's a bad idea to use recursion when you don't have to since it pollutes the stack with method calls needlessly. If the user enters a wrong file enough times, it will crash the JVM. On Java this isn't so bad, but in other programming languages this is a serious security flaw.

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.
This also shows how Java is kind of a pain for beginners, because the basic input/output stuff that beginners want to do is way too crufty.

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
When I was taught Java, the really basic stuff was taught using a package called Console that took care of the really basic IO and graphics stuff. Later on, they taught us Swing with more graphical ways to get input, and then Scanner/BufferedReader/FileWriter/etc.

Paolomania
Apr 26, 2006

ShardPhoenix posted:

This also shows how Java is kind of a pain for beginners, because the basic input/output stuff that beginners want to do is way too crufty.

I would totally recommend Python over Java to any beginners. A good intro to programming in Python should give them a soft introduction to exceptions so that by the time they get to the mandatory exception handling in Java it is merely a verbose PITA instead of inscrutable voodoo.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Just show them how to convert everything into a Runtime exception :unsmigghh:.

No Safe Word
Feb 26, 2005

MEAT TREAT posted:

Just show them how to convert everything into a Runtime exception :unsmigghh:.

Why bother when you can just add throws Exception everywhere?

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
Why bother throwing anything? Just suppress it! If the stack trace is never printed, that means it never happened!

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

Ensign Expendable posted:

Why bother throwing anything? Just suppress it! If the stack trace is never printed, that means it never happened!

Sounds like you are an enterprise architect.

emonkey
Jun 30, 2007
So when making games, you usually need some sort of 3d math library. You can define this like so:

code:
class Vec3
{
   public float X;
   public float Y;
   public float Z;

   public Vec3( float x, float y, float z )
   {
      X = x;
      Y = y;
      Z = z;
   }

   public static Vec3 add( Vec3 a, Vec3 b )
   {
      return new Vec3(a.X+b.X, a.Y+b.Y, a.Z+b.Z);
   }

   public static Vec3 scale( Vec3 a, float b )
   {
      return new Vec3(a.X*b, a.Y*b, a.Z*b );
   }
}
then you can use it like so:

code:
Vec3 a = new Vec3(1.0f,2.0f,3.0f);
Vec3 b = new Vec3(4.0f,5.0f,6.0f);

Vec3 c = Vec3.scale(Vec3.add(a, b), 7.0f);
Other languages with operator overloading make the syntax nicer, but alas. The big problem with this is, is in a game it creates a TON of new objects and will cause garbage collection to hitch constantly, destroying all fun. An optimization called escape analysis can remove these allocations, but it's not something that is easy to trust, and not all jvms do this, the android one does not, for example.

The best way is to not use objects at all, but with the lack of multiple return types, or pass by references, you cannot make an easy to use library, and end up having to inline everything, so the code becomes:

code:
float a_x = 1.0f;
float a_y = 2.0f;
float a_z = 3.0f;

float b_x = 4.0f;
float b_y = 5.0f;
float b_z = 6.0f;

float c_x = (a_x + b_x) * 7.0f;
float c_y = (a_y + b_y) * 7.0f;
float c_z = (a_z + b_z) * 7.0f;
At least, this is my understanding of this problem. This is a trivial example, but if you wanted to make something more complex, like find the distance between a point and a line, you can never create a function that does this, you have to re-do the math every time.

How the F can you make something like this fast and usable?

baquerd
Jul 2, 2007

by FactsAreUseless

emonkey posted:

How the F can you make something like this fast and usable?

JNI to a native 3D library.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Use fixed-point representations of vector components packed into longs, allowing you to store and pass vectors as single primitive elements! :q:

edit: But seriously, this seems like a justification for a mutable vector type. Immutable datatypes are nice for a lot of things, but they result in more GC pressure. It's a tradeoff, and your use case seems to indicate mutability is a better deal.

Internet Janitor fucked around with this message at 22:24 on Jul 27, 2011

emonkey
Jun 30, 2007

baquerd posted:

JNI to a native 3D library.

JNI has a significant performance hit associated with it as well iirc.

emonkey
Jun 30, 2007

Internet Janitor posted:

Use fixed-point representations of vector components packed into longs, allowing you to store and pass vectors as single primitive elements! :q:

edit: But seriously, this seems like a justification for a mutable vector type. Immutable datatypes are nice for a lot of things, but they result in more GC pressure. It's a tradeoff, and your use case seems to indicate mutability is a better deal.

Well even with mutable vector types you just reduce the number of vectors being allocated, not remove them entirely. You end up having to create static temporary vectors just for a function to use, and god forbid you call anything recursively.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Add a preprocessor to your compilation chain and use macros.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
I'm probably going to regret posting this, but the more I think about packing stuff into longs the more I think it might not be that bad:
code:
public class Vectors {

	static final int COMPONENT_MASK = (1 << 22)-1;
	
	public static long vector(int x, int y, int z) {
		return ((x & COMPONENT_MASK) << 42) |
		       ((y & COMPONENT_MASK) << 21) |
		        (z & COMPONENT_MASK);
	}
	
	public static int x(long v) { return (int)((v >> 42) & COMPONENT_MASK); }
	public static int y(long v) { return (int)((v >> 21) & COMPONENT_MASK); }
	public static int z(long v) { return (int)(        v & COMPONENT_MASK); }
	
	public static long add(long a, long b) {
		return vector(x(a) + x(b), y(a) + y(b), z(a) + z(b));
	}

	public static long scale(long a, int b) {
		return vector(x(a)*b, y(a)*b, z(a)*b);
	}

	public static int dot(long a, long b) {
		return x(a)*x(b) + y(a)*y(b) + z(a)*z(b);
	}
}
You'd have 21 bits of precision per component, which is actually enough for a lot of things. Then just import all these utility methods statically and you're set. I think I need to stop programming in assembly for a while.

zootm
Aug 8, 2006

We used to be better friends.

MEAT TREAT posted:

Just show them how to convert everything into a Runtime exception :unsmigghh:.
I know that UnhandledException is probably my most-used Apache Commons class...

Adbot
ADBOT LOVES YOU

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Java 7 was just released.

So how long until Eclipse supports it?


e: And is there a good list of what's new in 7?

Malloc Voidstar fucked around with this message at 16:57 on Jul 28, 2011

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