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
Sedro
Dec 31, 2008
This doesn't actually do anything:
code:
	public void clear(){
		p_02Node<T> current=head.getNextNode();
		while(current!=head){
			p_02Node<T> next=current.getNextNode();
			current=null;
		}
	}
Setting current=null just nulls out the local reference to the node and has no effect on the state. Clear is really easy in Java:
code:
void clear() {
    head = null;
    tail = null;
}
Also you probably want to store the count as a field.

Sedro fucked around with this message at 16:21 on Apr 16, 2012

Adbot
ADBOT LOVES YOU

pigdog
Apr 23, 2004

by Smythe

iscis posted:

I'm having trouble implementing some methods of a doubly linked list, if anyone could point me in the right direction I'd appreciate it.
code:
public class p_02<T> extends p_02Node {

Don't use names like p_02, p_02Node, temp etc. Name things so looking at a name would tell the reader what they are.

Any particular reason you wouldn't just use LinkedList? That is, if you really need a linked list in the first place, as opposed to normal ArrayList.

ComptimusPrime
Jan 23, 2006
Computer Transformer

pigdog posted:

Any particular reason you wouldn't just use LinkedList? That is, if you really need a linked list in the first place, as opposed to normal ArrayList.

He is in an intro to data structures class. I am pretty sure.

Long John Power
Sep 11, 2001

Does anyone have any experience using org.apache.poi.ss.usermodel.Cell?

I am trying to pull in the value of a few cells in an excel file.

The problem at the moment is that getCachedFormulaResultType() seems to be returning "0". Even when a valid formula is in the box.

For comparison if I use, getCellFormula() It outputs the cell formula as you would expect. eg "=SUM(C10:C12)"

Does anyone have any idea why this would be happening?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Just as a wild guess, have you modified the formula or any related data since reading the cached formula result? Has the document ever been opened in Excel before? The Excel file format has fields for keeping track of calculation results, but the specs don't require any of that information to be there.

Long John Power
Sep 11, 2001

Internet Janitor posted:

Just as a wild guess, have you modified the formula or any related data since reading the cached formula result? Has the document ever been opened in Excel before? The Excel file format has fields for keeping track of calculation results, but the specs don't require any of that information to be there.

Well I have tried with original ones, modified ones, and brand new ones! All no joy.

I also have documents that have and have never been opened in Excel before.

It would make sense from what I am seeing if this info was just never saved :(

EDIT

Turns out it was a schoolboy error on my part, I needed to do something like this...

code:
 switch(cell.getCachedFormulaResultType()) {
            case Cell.CELL_TYPE_NUMERIC:
               System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_String:
                System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                break;
}
To make sure I was printing int/string.

Long John Power fucked around with this message at 14:46 on Apr 18, 2012

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I need some help with java sockets and BufferedReaders/BufferedWriters.

I'm trying to set up a server/client so that after connecting, input entered by the client will be displayed server side, until the client inputs a null string. After the null input, the roles reverse, until the server inputs a null string, at which point the connection terminates and the server readies itself for another client.

My problem is getting my BufferedWriter to 'flush' the user's input. Upon establishing a connection, both the Server and Client create BufferedReader/BufferedWriter as follows:

code:
BufferedWriter clientOut = new BufferedWriter(
			   new OutputStreamWriter(
			   clientSocket.getOutputStream() ));


BufferedReader serverIn =  new BufferedReader(
			   new InputStreamReader(
			   clientSocket.getInputStream() ));
(This is the clientside, but serverside is similar). Client then enters a loop:

code:
String line = null;
	while( (line = userIn.readLine()) != null ){
		clientOut.write( line , 0, line.length() );
		clientOut.flush();
*		clientOut.close();
	}
Where userIn is a BufferedReader made from System.in.

At this point the server is in its own loop:

code:
while( (clientLine=clientIn.readLine()) != null){
	System.out.println(clientLine);
}
Which is supposed to read the flushed line from clientOut and print it locally.

My first attempt didn't have the line marked *, and the result was that the server never ever printed anything until the client process was violently killed, at which point it prints everything that the client has input.

When I include the line *, the server will print the first input from the client, but when the client makes their second input, an error is returned since clientOut is destroyed.

When I include the construction of clientOut inside the while loop (this seems excessive to me but may, for all I know, be standard practice), the server again successfully prints the first input from the client, but the second client input produces an error since (much to my surprise) clientOut.close() seems to close clientSocket (since clientOut invokes clientSocket in its construction I guess?)



Really could use some pointers. Thanks.

ComptimusPrime
Jan 23, 2006
Computer Transformer
readLine will only return once it encounters a new line (which happens in the terminal when you press enter). New lines are not automatically entered in to an output stream unless you have a method called something like "writeLine". BufferedWriters have a method "newLine", which you can call after each write. Don't close the socket and reopen it. Hopefully this will get you on your way.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Ahhh, drat, thanks. I essentially replaced clientOut.write( line ) with clientOut.write( line + "\n" ) (probably poor form) and things smoothed out from there.

Thanks again.

Airconswitch
Aug 23, 2010

Boston is truly where it all began. Join me in continuing this bold endeavor, so that future generations can say 'this is where the promise was fulfilled.'
Another student question. How do I access a specified element in a queue? Say I wanted to invoke the method example() in the first item in a queue?

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Airconswitch posted:

Another student question. How do I access a specified element in a queue? Say I wanted to invoke the method example() in the first item in a queue?

queue.poll() to get and remove the head object. queue.peek() to get the first object but leave it on the queue.

Remember you cann't get a specific object in a queue. Queues are First In First Out (FIFO). If you want to get a specific object out you will want to use a list.

lamentable dustman fucked around with this message at 19:53 on Apr 18, 2012

Airconswitch
Aug 23, 2010

Boston is truly where it all began. Join me in continuing this bold endeavor, so that future generations can say 'this is where the promise was fulfilled.'
That's fine, I just need the first item. So it would be something like line.peek().gettime() to invoke gettime() on the first item?

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Yes but the object will stay at the head of the queue so next time you do line.peek().gettime() you will be getting time from the same object.

Another thing, you will want to do some kind of check to see if the object in the queue is null or not. Generally it is done like this:

code:
if(queue.peek() != null){
   queue.poll().gettime();
}

Thermopyle
Jul 1, 2003

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

I have a method that takes a parameter. Sometimes, depending on the state of the device this code is running on, some possible values of that parameter are valid, other times those same values are invalid.

Which exception should I throw when they are invalid, or should I create my own exception (subclassed from what)? Or should I rethink my design or something?

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried
Something subclassed from InvalidStateException, I reckon.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Blacknose posted:

Something subclassed from InvalidStateException, I reckon.

IllegalStateException, but FYI that extends RuntimeException. If the clients of that method can't reasonably recover from that error then by all means use it. If they can handle it, then you should subclass from Exception so that they have to handle it.

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried
Oops, been coding javascript for 5 months, I think my brains gone a bit funny.

Thermopyle
Jul 1, 2003

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

MEAT TREAT posted:

IllegalStateException, but FYI that extends RuntimeException. If the clients of that method can't reasonably recover from that error then by all means use it. If they can handle it, then you should subclass from Exception so that they have to handle it.

Yeah, they can recover. I'll just make something from Exception.

(I don't write Java much, so wasn't sure if there was a good provided exception for this)

pigdog
Apr 23, 2004

by Smythe
Are you sure you even need to throw an exception, rather than implementing, say, Strategy pattern to choose a different algorithm to handle different states?

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Thermopyle posted:

I have a method that takes a parameter. Sometimes, depending on the state of the device this code is running on, some possible values of that parameter are valid, other times those same values are invalid.

Which exception should I throw when they are invalid, or should I create my own exception (subclassed from what)? Or should I rethink my design or something?
Is it a coding (human) error? If yes, IllegalArgumentException. If no, whatever you're doing with Exception probably.

Hidden Under a Hat
May 21, 2003
I need to send software that I've designed and coded to Germany, and I'm wondering if there are any special considerations I need to take to make sure it runs the same on an international computer. My software makes frequent timing control checks based on time-of-day to control devices connected via sockets.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
In Java everything character and time related should accept a localization parameter, if one is not provided it defaults to the local computer's settings, which means that if you haven't added those parameters, the defaults might lead to different behavior.

Thermopyle
Jul 1, 2003

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

Aleksei Vasiliev posted:

Is it a coding (human) error? If yes, IllegalArgumentException. If no, whatever you're doing with Exception probably.

Hmm. Well it could be a human error. The user of the method could check the validity of the parameter before calling the method.

To be clear, this method deals with location fixes on an Android device. The parameter is a location provider which could be GPS, or network, or some other craziness. Sometimes the X location provider isn't available, sometimes it is.

I guess it depends on how I document the method to other users, doesn't it? "Always check availability of provider before passing it." Or "Throws X Exception if provider isn't available."

Which one would other users prefer?

Doctor w-rw-rw-
Jun 24, 2008

Thermopyle posted:

Yeah, they can recover. I'll just make something from Exception.

(I don't write Java much, so wasn't sure if there was a good provided exception for this)

I don't generally like checked exceptions. Not from a "does it work" or "does it make sense" point of view, but a "how much time do you spend doing exactly the same thing" point of view. I go with unchecked because I don't have to add a bunch of boilerplate or worry about it infecting interfaces. For example when there's no reasonable expectation of a JSON parsing error or IO error but I have to handle it anyway, I'm kind of just...blah. More catching, logging, and re-throwing wrapped in a RuntimeException anyways.

Not that my way is necessarily the only or best way to handle exceptions, though.

Hidden Under a Hat
May 21, 2003

trex eaterofcadrs posted:

In Java everything character and time related should accept a localization parameter, if one is not provided it defaults to the local computer's settings, which means that if you haven't added those parameters, the defaults might lead to different behavior.

Could you give me an example of a "localization parameter"?

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

Hidden Under a Hat posted:

Could you give me an example of a "localization parameter"?

Locale.US
TimeZone.getTimeZone("GMT-8")

Now if you're doing things with relative times that have NOTHING AT ALL to do with wall time or durations of Days/Weeks/Months/Years, then by all means, System.currentTimeMillis() (or nanoTime()) is probably ok for your usage.

Doctor w-rw-rw-
Jun 24, 2008

Hidden Under a Hat posted:

I need to send software that I've designed and coded to Germany, and I'm wondering if there are any special considerations I need to take to make sure it runs the same on an international computer. My software makes frequent timing control checks based on time-of-day to control devices connected via sockets.

Yes. Use Joda Time if time values are important to your app. Do not use Java's date/time.

If you need to schedule periodic tasks then consider and evaluate Quartz rather than implementing your own logic. It's easy to embed.

Hidden Under a Hat
May 21, 2003
My entire software relies on these methods for getting time values to do timing control checks:

code:
    public static String getFormattedTimeStamp(String format){

        Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
        String currentTime = new SimpleDateFormat(format).format(currentTimestamp);
        return currentTime;
    }

    public static int getTimeInMinutes(){
        return convertTimeToMinutes(getFormattedTimeStamp("HH:mm"));
    }
    
    public static int getTimeInSeconds(){
        return convertTimeToSeconds(getFormattedTimeStamp("HH:mm:ss"));
    }

    public static int convertTimeToMinutes(String time){

        try{
            int hours = Integer.parseInt(time.split(":")[0])*60;
            int minutes = Integer.parseInt(time.split(":")[1]);
            return hours+minutes;
        }
        catch(NumberFormatException ex){
            return 0;
        }
    }
    
    public static int convertTimeToSeconds(String time){

        try{
            int hours = Integer.parseInt(time.split(":")[0])*3600;
            int minutes = Integer.parseInt(time.split(":")[1])*60;
            int seconds = Integer.parseInt(time.split(":")[2]);
            return hours+minutes+seconds;
        }
        catch(NumberFormatException ex){
            return 0;
        }
    }

What would I do differently to ensure international support?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
So what do you do with the time? If you do not care about wall time or durations of time longer than hours, you shouldn't even bother with Calendar and Date.

Paolomania
Apr 26, 2006

A time-naive question: how is keeping everything in UTC milliseconds (ala System.currentTimeMillis()), and just converting to Calendar/SimpleDate/etc for human consumption, insufficient as an internationalizable time keeping solution? (just talking representation issues here - i.e. aside from the more complicated issues of time consistency across a network such as assuming the system time is set properly vs. relying on an external time server)

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Hidden Under a Hat posted:

My entire software relies on these methods for getting time values to do timing control checks:

What would I do differently to ensure international support?

I don't see what you have to worry about unless you are comparing time stamps from different regions. Time intervals are the same of course and will be based off of the client's clock.

Max Facetime
Apr 18, 2009

The I-know-enough-about-time-to-know-I-don't-know-nearly-enough answer: it's a good starting point that may well take you as far as you'll ever want to go.

E:

lamentable dustman posted:

I don't see what you have to worry about unless you are comparing time stamps from different regions. Time intervals are the same of course and will be based off of the client's clock.

Time intervals around DST changes are another thing.

Max Facetime fucked around with this message at 16:44 on Apr 20, 2012

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Yeah not all days are 24 hours, leap seconds and DST changes will affect time.

Paolomania
Apr 26, 2006

But UTC is not affected by DST and accommodates for leap seconds to stay in accord with UT, correct? In a Java world this leap-second accommodation occurs in the translation step from UTC millis to an actual date, and therefore if your back end only deals with UTC millis and you use a properly conforming library to convert a system-relative-accurate UTC millis-since-Jan-1-1970 to a specific date, then you do not need to worry about any of this, correct? Like I said, I am not experienced in more advanced time keeping, these are just my pre-conceptions from what I know about dealing with time in Java. If my assumptions are wrong I would love to be educated.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
You make a good point. Time is such a complex and nuanced topic that, like I am in, I know enough to say I don't know poo poo, and I use weasel words a lot.

That said, specifically about S.cTM: if you check the JavaDoc:
http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#currentTimeMillis()

JDK SE 6 posted:

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

Now currentTimeMillis() is perfectly ok for many (most?) tasks, but you really need to understand your problem domain to know how timekeeping should be accomplished, and be well educated about the options and how your app needs to respond.

Mobius
Sep 26, 2000
I'd like to use a simple web framework on a personal project that I may make open-source in the future. I know Struts from work, but that's really overkill for this. I'm thinking about WEB4J. Has anyone here used it? Or have other recommendations, instead? I'm looking for something that will both get the job done and give me a chance to learn something practical.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
At the risk of sounding like a broken record, have you looked at grails?

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
I'm trying to do some operations on the contents of a LinkedList. As you know, Nodes for the LinkedList class contain the generic data type "Object". The LinkedList class we are using for this assignment is supposed to be loaded with Nodes that contain a special class called "Jobs" that has it's own methods, but the constructor is still supposed to take any object.

I'm trying to run these methods on the Jobs within my LinkedList, but the compiler only recognizes the data in these nodes as generic Objects, not Jobs and I get the "cannot find symbol" error. Here's a snipit of my code where the errors are happening (prime.data.run(100))

code:
         while (waitQ.getSize() > 0){
            LinkedList.Node prime = waitQ.getHead();
            for(int i = 0; i < waitQ.getSize(); i++){
					prime.data.run(100);
               System.out.println(prime.data.getClass() + "\n" + prime + "\n" + prime.data);
               prime = prime.next;
            
            	
            }
				System.out.println(waitQ);
         	
         	
         
         
         }//end while
I've fooled around with this for a while. When I print out "prime.data" it lists a memory address for a Job, but when I use the toString for the entire LinkedList, it reports it to be a LinkedList.Node

Harold Ramis Drugs fucked around with this message at 04:42 on Apr 23, 2012

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

You have to cast prime.data back to "Jobs" in order to get at its methods.

Adbot
ADBOT LOVES YOU

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post

carry on then posted:

You have to cast prime.data back to "Jobs" in order to get at its methods.

Would that be using the "(Job)" cast in front of the call? If I do that, the program will compile but break when I try to run it with a Null Pointer Exception. Here's what I did:

code:
					waitJob = (Job)prime.work;
					waitJob.run(100);

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