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
csammis
Aug 26, 2003

Mental Institution

Outlaw Programmer posted:

According to this site, the JVM will take care of any endian problems for you. I guess you only run into endian problems if your output is being read by a non-Java process (or your file is being generated by a non-Java process).

You could also run into problems if you were using the FloatBuffer to encapsulate data read from a binary-packed network stream, which would probably be in Network Byte Order (big endian).

Adbot
ADBOT LOVES YOU

JingleBells
Jan 7, 2007

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

schzim posted:

JavaSeverFaces and JavaServerPage Goons to the rescue please k thnx.

I have a string in a session attribute.

I am working with an off the shelf package which includes some jsf components.
I am using this component and want to set the value of one of the parameters to a string expression using the session variable.

....
<xxx:productView id="something"
color = "red"
filename = "C:/webdir/foo/"${session.getAttribute("fileName")}"
shape = "line"
//other stuff
</xxx:productView>

This does not seem to be able to work in any way that I have tried. I am certainly a JSP/JSF retard. So please educate me.

I believe what you're after is the pageContext.setAttribute method, to be used like so:
code:
<%
pageContext.setAttribute("fileName", "C:/webdir/foo/" + session.getAttribute("fileName"));
%>
..
..

<xxx:productView id="something"
color = "red"
filename = "${fileName}"
shape = "line"
//other stuff
</xxx:productView>

drunkill
Sep 25, 2007

me @ ur posting
Fallen Rib
I'm stupid aren't I?

I'm new to Java, infact, programming all together. Started a part time course and we've got Java and Databases as my classes. Databases is pretty simple but I just can't get to grips with Java.

In this exercise we're supposed to get input on various things, first name, last name, age, height, gender and if they can drive yet.

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.");
	}
}
I know I've got to do an IF for the drivers license, so it comes out as "You can drive TRUE/FALSE" But i'll get onto that in awhile.

edit: I'm also JCreator to compile the code, but since I installed it at home today, when I run the program or file, I don't get the black box which I got at uni wehn using it. I get the build output so I can view any errors, but when at Uni the black box would pop-up and display the errors as well, if the program worked it'd be where you input stuff to make the program run etc. But for some reason it's not working at home.

drunkill fucked around with this message at 07:58 on Aug 6, 2008

the onion wizard
Apr 14, 2004

drunkill posted:

I'm stupid aren't I?

Don't worry, it'll all come together and start making sense pretty quickly.

drunkill posted:

edit: I'm also JCreator to compile the code, but since I installed it at home today, when I run the program or file, I don't get the black box which I got at uni wehn using it. I get the build output so I can view any errors, but when at Uni the black box would pop-up and display the errors as well, if the program worked it'd be where you input stuff to make the program run etc. But for some reason it's not working at home.

I'm not familiar with JCreator, but are you able to compile and run your code from the command line?

eg:
javac Exercise1.java
java Exercise1

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Well another problem with your code is that you trying to save their name as an int when you should be saving them as Strings. The only things that are ints are their age and height. You should also tell them to specify their height in inches, that way you don't have to parse feet and inches.

You are also missing the types for the fields first, last, hieght, gender, and your drivers license field is repeating.


edit: About JCreator, don't worry about the black box, your output will be in a small white box at the bottom of the screen. The reason you can't type in it is because of all the compiler errors I mentioned above.

Janitor Prime fucked around with this message at 13:04 on Aug 6, 2008

Startacus
May 25, 2007
I am Startacus.
Hey, I can use some help here. I have a program where I have an array of objects and I want to output them to a .csv file. Right now the object just holds variables for name and grade, both of them are strings (Although I should parse an int from the grade but I can do that later).


So essentially I want to output to a fie the name and the grade separated by a comma.


I can't figure out what kind of stream I need to use or how I would set it up.

I would basically want this:

code:
 for(int i = 0 ; i < objectSize; i++)
  {
   System.out.println(Student[i].getName() + "," + Student[i].getGrade());
  }
Except, rather then printing it to the console, I want that written to a file.

Can anyone help me out please?

JingleBells
Jan 7, 2007

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

Startacus posted:

Hey, I can use some help here. I have a program where I have an array of objects and I want to output them to a .csv file. Right now the object just holds variables for name and grade, both of them are strings (Although I should parse an int from the grade but I can do that later).


So essentially I want to output to a fie the name and the grade separated by a comma.


I can't figure out what kind of stream I need to use or how I would set it up.

I would basically want this:

code:
 for(int i = 0 ; i < objectSize; i++)
  {
   System.out.println(Student[i].getName() + "," + Student[i].getGrade());
  }
Except, rather then printing it to the console, I want that written to a file.

Can anyone help me out please?
This should do it:
code:
//Add these at the top
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
//This writes the file
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("MyFile.txt"));
 for(int i = 0 ; i < objectSize; i++)
  {
   writer.write(Student[i].getName() + "," + Student[i].getGrade() + "\r\n");
  }
writer.close();
} catch(IOException ioe) {
   //You should probably do something more sensible here
   System.out.println("ARGH, exception: " + ioe);
}
This will write MyFile.txt *somewhere* on your file system. If your running it from the command line it'll be in the directory you're in, if you're in an IDE it'll be god knows where. You can pass an absolute path if you like, such as "C:/code/work/output.txt" (forward slashes in java on windows work just fine)

JingleBells fucked around with this message at 01:25 on Aug 9, 2008

Startacus
May 25, 2007
I am Startacus.

JingleBells posted:

This should do it:
code:
//Add these at the top
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
//This writes the file
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("MyFile.txt"));
 for(int i = 0 ; i < objectSize; i++)
  {
   writer.write(Student[i].getName() + "," + Student[i].getGrade() = "\r\n");
  }
writer.close();
} catch(IOException ioe) {
   //You should probably do something more sensible here
   System.out.println("ARGH, exception: " + ioe);
}
This will write MyFile.txt *somewhere* on your file system. If your running it from the command line it'll be in the directory you're in, if you're in an IDE it'll be god knows where. You can pass an absolute path if you like, such as "C:/code/work/output.txt" (forward slashes in java on windows work just fine)

That works great except for some reason it doesn't add a comma every other time. So I will have a name and grade separated by a comma on one line, like it's supposed to. Then on the next line I will just have a name and the line after that, just a grade. It does that back and forth, weird.

JingleBells
Jan 7, 2007

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

Startacus posted:

That works great except for some reason it doesn't add a comma every other time. So I will have a name and grade separated by a comma on one line, like it's supposed to. Then on the next line I will just have a name and the line after that, just a grade. It does that back and forth, weird.

It might be worth adding .trim() to your calls to getName() and getGrade() then, it sounds like your values may have carriage returns/new lines in it?

code:
 writer.write(Student[i].getName().trim() + "," + Student[i].getGrade().trim() + "\r\n"); 

Startacus
May 25, 2007
I am Startacus.

JingleBells posted:

It might be worth adding .trim() to your calls to getName() and getGrade() then, it sounds like your values may have carriage returns/new lines in it?

code:
 writer.write(Student[i].getName().trim() + "," + Student[i].getGrade().trim() + "\r\n"); 

When I add the trim method to the functions I get a null pointer exception at that line. My returns don't have new lines, all that's in the two get function is "return variableName".

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!

Fehler
Dec 14, 2004

.

Startacus posted:

When I add the trim method to the functions I get a null pointer exception at that line. My returns don't have new lines, all that's in the two get function is "return variableName".
Then you probably have some objects in there where the name and/or the grade is not set (null). Also, the variables themselves might have newlines in them, depending on where you get their values from.

Startacus
May 25, 2007
I am Startacus.

Fehler posted:

Then you probably have some objects in there where the name and/or the grade is not set (null). Also, the variables themselves might have newlines in them, depending on where you get their values from.

The information is being imported from another .csv file. The information is just "name,grade"


And yes, I do have a lot of objects set to null, I will have to go through where I assign all of the information to figure out what I did.

Startacus
May 25, 2007
I am Startacus.
it seems that now I need a little help on the reading front, this is what is causing the problems with the write. This is what I have thus far:

code:
			//Creates the input and output streams
			FileInputStream inFile = new FileInputStream(GlobalDataStore.file);
			DataInputStream in = new DataInputStream(inFile);

			//Creates a new byte array to read file
			byte[] b = new byte[in.available()];

			//Fully reads the file into the byte array
			in.readFully(b);

			//Closes the input stream
			in.close();

			//Creates a new string array to receive the input from the file
			String str = new String(b, 0, b.length, "Cp850");
			String[] assignValues = null;

			//Splits the input at every comma and stores it into an array
			assignValues = str.split(",");
The problem is, rather then placing each value of the split in it's own array index, it's just placing a newline character.

So rather then having assignValues[0] be a name and assignValues[1] be a grade, assignValues[0] is both a name and a grade separated by a newline.

Can someone help me fix this little problem?

Twitchy
May 27, 2005

Startacus posted:

Can someone help me fix this little problem?

You could either firstly split the values into individual lines then split based on the coma into a new array, or use regular expression in the split method like split("[,\\n]") (I haven't tested that this works but it should be alright).

Also it seems odd that you have 2 different pieces of information in the same array, you'd probably be better making a small class with name and grade fields and have an array of those to store the information. Depends what you're doing it for I guess :).

Twitchy fucked around with this message at 14:51 on Aug 11, 2008

Startacus
May 25, 2007
I am Startacus.

Twitchy posted:

You could either firstly split the values into individual lines then split based on the coma into a new array, or use regular expression in the split method like split("[,\\n]") (I haven't tested that this works but it should be alright).

Also it seems odd that you have 2 different pieces of information in the same array, you'd probably be better making a small class with name and grade fields and have an array of those to store the information. Depends what you're doing it for I guess :).

Wow, thanks a lot, that regular expression worked like a charm.

Yea, those values can stay as Strings. What I'm basically doing is writing a program for my old highschool that will take their schools roster and automatically assign all the students auditorium seats and locker numbers. I've only taken one Java class second semester last year and I wanted to refresh my memory before I leave for college because I'm going to be skipping the intro classes though.


I appreciate the help though, we didn't really cover file I/O too indepthly in the class so I'm a bit shaky on that material.

perihare
Mar 12, 2004
pika pika!
What's the easiest way to register a Windows file association from a Java program? For example, if I want my program to open all files with a .crap extension automatically, how do I register that with Windows?

Also, how do I get the current Windows idle time, e.g. how long the user has not given any input to the computer? I realize that I might be better served with C++/C# for these problems, but...

perihare fucked around with this message at 00:32 on Aug 12, 2008

Entheogen
Aug 30, 2004

by Fragmaster
I have a very weird problem. I made a web-start application that utilizes Java OpenGL bindings. It runs fine on Windows, but on linux and solaris it starts fine but freezes at one point. And there is no way for me to close the window, it is basically non-responsive at all.

What could be causing this? Usually this happens when I switch shaders in my program, or when I start generating iso surface. I don't believe I use any native resources by that point since I read the shaders in at the start and the program doesn't freeze right after I read in the volume data itself.

What could potentially be causing this? If it would help, here is the application itself - http://giga2.cs.ohiou.edu/~neiman/jstart/jung/volume.jnlp Try to load a file in (please do not load anything higher than 15mb), and try to switch shaders.

The Java console freezes as well by this point so there is no way for me to know if any exceptions are thrown or anything.

Entheogen
Aug 30, 2004

by Fragmaster
Ok, I compiled my project in netbeans in ubuntu and ran it that way, and it was fine. This problem only appears to be with web start version of my application.

Fehler
Dec 14, 2004

.
Does it make a difference whether you request full permissions for your app in the JNLP file?

Entheogen
Aug 30, 2004

by Fragmaster

Fehler posted:

Does it make a difference whether you request full permissions for your app in the JNLP file?

Yes. My app needs to be able to write and read files to work. So it needs full permissions. You might be on to something. I think this might be just web start's version of JOGL binaries for linux that are messing this up tho.

Alan Greenspan
Jun 17, 2001

a_passerby posted:

What's the easiest way to register a Windows file association from a Java program? For example, if I want my program to open all files with a .crap extension automatically, how do I register that with Windows?
What I do is to create a .reg file with the necessary information and execute "regedit /S filename.reg" from Java.

Chuu
Sep 11, 2004

Grimey Drawer
Studying for the SCJP and have some syntax question.

1. Right now the following program prints "OHGOD" (as expected). How do I change it so it prints out "0 1 2 3" using the "x" variables defined in the nested classes?

code:
public class Nested{


    public static void main(String... args){
	TestClass.NestedTest.NestedNestedTest test = new TestClass().new NestedTest().new NestedNestedTest();

	test.printStuff();

    }
}

class TestClass{
    int x = 0;

    class NestedTest{
	int x = 1;
	
	class NestedNestedTest{
	    int x = 2;
	    
	    void printStuff(){
		int x = 3;
		System.out.println("OHGOD");
	    }
	}
    }
}
2. Is there a document somewhere that explains local inner classes and static nested classes clearly? The java tutorial explains Nested classes clearly but doesn't really go into local inner or static nested classes at all. Are static local inner classes legal? Are you allowed to add nested classes to local classes?

Chuu fucked around with this message at 15:07 on Aug 15, 2008

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
That's loving retarded, why would you ever want that.

Since your fields aren't private and they are all in the same package, I think you should be able to access each one's X by placing the class name dot x.

TestClass.x NestedTest.x NestedNestedTest.x and x

LakeMalcom
Jul 3, 2000

It's raining on prom night.
I think you actually want TestClass.this.x and NestedTest.this.x ... etc.

defmacro
Sep 27, 2005
cacio e ping pong
Recommendations for a Java memory profiler? I don't want to attach it to any IDE as I need to run it all remotely. We're using Java 1.5.

Chuu
Sep 11, 2004

Grimey Drawer

MEAT TREAT posted:

That's loving retarded, why would you ever want that.

Since your fields aren't private and they are all in the same package, I think you should be able to access each one's X by placing the class name dot x.

TestClass.x NestedTest.x NestedNestedTest.x and x

I agree that it's retarded, but a large part of the exam are things that you would never do in real life, but are there to see if you understand the language spec.

That example was pretty simple, I could make it more complex to stop you from "cheating," but what I really want to know is how to fully qualify names of shadowed data members. The only way I know how to do it is with "this" but that isn't enough with multiple-nested classes.

edit : Actually, if you don't think Anonymous classes are retarded, this sort of thing could happen really easily with Anonymous classes, in that you need a reference to an object that's not the top level or bottom level class.

Chuu fucked around with this message at 21:01 on Aug 15, 2008

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Maybe the super keyword can help you. I don't know if it actually works for anything other than methods.

Outlaw Programmer
Jan 1, 2008
Will Code For Food
This will print out what you want (inside the printStuff() method):

code:
System.out.println(TestClass.this.x + " " + NestedTest.this.x + " " + NestedNestedTest.this.x + " " + x );
Notice the use of ClassName.this; that's how you access the "this" reference of the outer object. As previously noted, what you're trying to to is pretty crazy but you will often run into something like this:

code:
class OuterClass
{
    private int outerMember = 12345;

    public void doStuff()
    {
        new Thread(new Runnable()
        {
            public void run()
            {
                // can't just use this.outerMember, because "this" now 
                // references the Runnable object.  Instead:
                System.out.println(OuterClass.this.outerMember);
            }
        }).start();
    }
}
See this Javaranch article on inner classes.

Personally, 99% of the time my inner classes are declared static.

zootm
Aug 8, 2006

We used to be better friends.

GT_Onizuka posted:

Recommendations for a Java memory profiler? I don't want to attach it to any IDE as I need to run it all remotely. We're using Java 1.5.
The IDE ones usually work remotely (certainly the NetBeans one can, I think it's pretty standard), but I've had better success with JProfiler remote. Not free, though.

Chuu
Sep 11, 2004

Grimey Drawer

Outlaw Programmer posted:

This will print out what you want (inside the printStuff() method)...:


Thanks a ton. That's the first use of Anonymous classes I've ever seen that actually seemed useful and not incredibly contrived.

Chuu
Sep 11, 2004

Grimey Drawer
Another syntax question! This time regarding class locks.

We have this code:

code:
class Lock1{

    public static void main(String[] args){
	Lock2 l2 = new Lock2();
	l2.counter();
	System.out.println("hi");
    }
}
Here are some different implementations of "Lock2." I'm a bit confused about them.

Implementation 1:

code:
class Lock2{
    static int count = 0;
    public static synchronized int counter(){
	return count++;
    }
}
No big deal. Checks to see if the class lock is available, since we only have 1 thread it is, excutes the code, prints "hi."

Implementation 2:

code:
class Lock2{
    static int count = 0;
    
    public static synchronized int counter(){
	synchronized(Lock2.class){
	    return count++;
	}
    }
}
According to the book I'm using to study, this should be equivalent to Implementation #1. Read naively, to me this means "Wait for the class lock before executing "counter()" then "Wait for the class lock before executing the return statement" i.e. it should automatically deadlock. Since it's functionally equivalent though, I assumed the "synchronized" keyword meant "somewhere in this method something is synchronized, not necessarily the entire method, unless you do not see a synchronized block, then the entire method is synchronized" i.e. it won't deadlock. Does what's expected, prints "hi". The problem is . . .

Implementation 3:
code:
class Lock2{
    static int count = 0;
    
    public static int counter(){
	synchronized(Lock2.class){
	    return count++;
	}
    }
}
This works too. So what exactly is the difference in #2 and #3, or is there something going on here that my trivial example isn't showing?

Chuu fucked around with this message at 12:48 on Aug 16, 2008

zootm
Aug 8, 2006

We used to be better friends.

Chuu posted:

According to the book I'm using to study, this should be equivalent to Implementation #1. Read naively, to me this means "Wait for the class lock before executing "counter()" then "Wait for the class lock before executing the return statement" i.e. it should automatically deadlock. Since it's functionally equivalent though, I assumed the "synchronized" keyword meant "somewhere in this method something is synchronized, not necessarily the entire method, unless you do not see a synchronized block, then the entire method is synchronized" i.e. it won't deadlock. Does what's expected, prints "hi". The problem is . . .
You've misinterpreted it. The synchronized keyword on a method signature always obtains a lock on the class object, even if there's a synchronized block inside the method. What you're missing is that the lock is held by the running thread - so when you run that inner block you already have the lock you ask to obtain.

Chuu posted:

So what exactly is the difference in #2 and #3, or is there something going on here that my trivial example isn't showing?
If you write code outside of the inner synchronized block in 2, it will still be synchronized, in 3 any code outside of there will not require the class lock to be held to run.

All three programs are equivalent but a synchronized block on the class within a synchronized method as in 2 will never do anything.

As an extreme example, here's another equivalent program:
code:
class Lock2 {
  static int count = 0;
  public static synchronized int counter() {
    synchronized(Lock2.class){
      synchronized(Lock2.class){
        synchronized(Lock2.class){
          synchronized(Lock2.class){
            return count++;
          }
        }
      }
    }
  }
}
Obtaining a lock you already have doesn't do anything. :)

zootm fucked around with this message at 15:00 on Aug 16, 2008

Chuu
Sep 11, 2004

Grimey Drawer
Ahh, ok, thanks a lot. I assumed they work the same was as mutexes on *nix.

To make sure, so if you have code like:

static synchronized void a(){...}
static synchronized void b(){...}

Any code which has control of the lock and executing a() will block any other threads from running b(), since the class level lock is associated with all static synchronized code in the entire class?

Chuu fucked around with this message at 17:20 on Aug 16, 2008

zootm
Aug 8, 2006

We used to be better friends.

Chuu posted:

Ahh, ok, thanks a lot. I assumed they work the same was as mutexes on *nix.

To make sure, so if you have code like:

static synchronized void a(){...}
static synchronized void b(){...}

Any code which has control of the lock and executing a() will block any other threads from running b(), since the class level lock is associated with all static synchronized code in the entire class?
Yes. Making a static method synchronized is really just syntactic sugar for enclosing its entire contents in synchronized( Whatever.class ). Similarly putting that modifier on an instance method is equivalent to wrapping the contents with synchronized( this ).

zootm fucked around with this message at 17:46 on Aug 16, 2008

Mill Town
Apr 17, 2006

Thread necromancy!

I'm looking for a good, lightweight Java database. It should run in <64M and use a well-known language. I was looking at SQLITE, but it seems that the database connector isn't very feature-complete yet. Anyone have other recommendations? Thanks.

1337JiveTurkey
Feb 17, 2005

Apache Derby claims to be fairly lightweight but I don't have much experience with it.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Java 6 comes with derby now if that means anything.

Mill Town
Apr 17, 2006

1337JiveTurkey posted:

Apache Derby claims to be fairly lightweight but I don't have much experience with it.

Sounds cool, but I see it takes SQL commands as raw text. Is there a sanitize function available? I can't find one by searching the site or Google. Thanks!

Adbot
ADBOT LOVES YOU

Outlaw Programmer
Jan 1, 2008
Will Code For Food
Can you clarify what you're looking for? You should be able to communicate with Derby/JavaDB via the JDBC interfaces, just like any other database. I think standard operating procedure for avoiding SQL injection is to just use PreparedStatements. I don't see any reason why JavaDB would be any different than any other vendor.

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