JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Who's your daddy!

SimpleTimeZone tz = new SimpleTimeZone(-10*24*60*60*1000,"10 days ago");
TimeZone.setDefault(tz);
System.out.println(new Date());

(dances round PC throwing punches in the air)

Celebrations maybe a bit premature - Max integer value limits offset to about +/- 24 days.
Is this enough?

stultuske commented: Actually that would be P. Brinkhof, but still a very impressive answer/sollution :) +15
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm having to fill in a few blanks in the requirements here, but probably:
Think about the real world. You go to a travel agent and they already have a list of destinations. They add you to their customer database, and then you can book a holiday.
So in Run you need a way to create Destinations and People. You'll need to keep a collection (eg ArrayList) for each of those. Then you can create Holiday by linking it to an existing Person and an existing Destination.

dantinkakkar commented: That I got... By my post, I meant that :) +4
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In real life its rare to very rare that you write your own versions of Java API classes like those. Even if there is some small optimisation you could do for some highly specific application, you would have to offset that against the disadvantages of using "roll your own" code rather than the highly designed, tested, documented, supported API versions.

Obviously, as training exercises they are really good - lots of methods and arrays and thread-related issues to learn about and practice - plus there's no need to spend ages defining and understanding some artificial problem description.

What speling misteak?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Maybe the problem is the Robot is pressing keys at the "hardware" level, not at the logical character level. So for upper-case A you need to press VK_SHIFT then VK_A, then release them both
On my UK keyboard ! is VK_SHIFT then VK_1, etc. But the code sequence for accented chars etc are completely different between my UK and French keyboards. The API JavaDoc for KeyEvent explains further.
Before you ask... no I don't know how get a map of chars to VK combinations for the currently installed keyboard layout - if you find out please post the answer here!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The JTextField stuff applies to a GUI text field, not to console output. Have a look at using printf instead of print, because that allows you to specify formatting for items when you print them at the console.. printf is a method of the PrintStream class, so you'll find the documentation in the API doc for PrintStream, although you may have to follow the links from there to get the whole story...
(Using the API doc is an essential skill for all Java developers - practice is good for you!)

shifat96 commented: Thanks! +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I don't mean this in an unkind way, but zeroliken's reference is to a very simple example. You're not going to find anything easier.
But here (from memory, so maybe slight errors) is a very short crib sheet:
Create your Cards as ordinary JPanels with whatever content
Set the frame's layout manager to new CardLayout() Add your cards to the JFrame, giving each a name, eg frame.add(card1, "C1"); In your button's response handler show the appropriate card frame.getLayout().show(frame, "C2");

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The normal pattern with a base clas and another that depnds on it (eg model & view) goes like this:

public static void Main(..) {
 Sudoku  theGame = new Sudoku ();
 SudokuValidator v = new SudokuValidator(theGame);

...
then in the constructor for SudokuValidator you take the instance of Suduku as a parameter and keep a copy

shean1488 commented: Thanks a lot! +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

What kind of set is only important if you have biggish sets or high transaction volumes. You don't need a TreeSet unless you are orried about keeping the netries sorted.
That code looks OK to me - could be simpler...
return ((State)o).getStateName().equalsIgnoreCase(getStateName());

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The API doc for HashSet shows it to be a subclass of Set, and the API doc for Set says "More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)"

So there's your answer. The implementation uses the equals(...) method of your objects to see if they are distinct. All classes inherit an equals method from Object, which tests them for being exactly the same instance. Many classes override this (eg String tests for both Strings containing the same sequence of chars). You can override equals for your State class and return a result based on the magic char that they contain.

ps: The answer to most questions is in the API doc. If it's really obscure you can download the source code for the whole API from Oracle and see how it really works.

pps: re overriding equals...
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.

In your case then simply returning the magic char should do it?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's hopeless trying to debug your code when you only supply tiny fragments of it. Plus you contradict yourself "still i getting nothing except the garbage value ... " or "but fine with above method".
And you still haven't posted the "garbage values" that I asked for twice.

This is really very very simple.
Open an ObjectOutputStream on the socket's output stream and write the userName and password to it by calling writeUTF twice. flush() the ObjectOutputStream for good luck.
At the receiving end open an ObjectInputStream on the socket's input stream and read the userName and password by calling readUTF twice.

If you can't make that work then post ALL the relevant code and an exact copy of all relevant output

NormR1 commented: 2 Stars for extra effort on this one +13
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Depends on exactly what you are trying to do, but in general
Exprfield.getDocument() will give you the Document object that handles the input and editing of what you see in the text field. Once you have the Document you can insert text at the caret or do whatever else you want

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You could Google java play video ... or did you want someone to do that for you?

stultuske commented: yet again ... Google to the rescue :) shame they don't think of it themselves +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry for previous terse reply - I just had a few seconds and thought it better brief than do nothing.
Anyway, more time now...
You can use any character-oriented streams - the ones you're familiar with would be an obvious choice. Here's a really good link about some problems that you 'll probably run into... and their solutions)
http://stackoverflow.com/questions/3643939/java-process-with-input-output-stream

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, in that case I can't see how you would improve on triple-nested 0-255 loops. You may be able to squeeze some more speed by doing some of the string conversion/formatting in the outer loops, eg so you don't evaluate a + "." + i + "." + j + "." 255 times with exactly the same values...
but in reality you would have to benchmark to be sure.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Google the ProcessBuilder class ...

v3ga commented: ty +3
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

This excerpt from, the URI API doc mau help?

A hierarchical URI is either an absolute URI whose scheme-specific part begins with a slash character, or a relative URI, that is, a URI that does not specify a scheme. Some examples of hierarchical URIs are:

http://java.sun.com/j2se/1.3/
docs/guide/collections/designfaq.html#28
../../../demo/jfc/SwingSet2/src/SwingSet2.java
file:///~/calendar

Looks to me like you may need new URI("file:///c:/sss.xps")

Zaad commented: Solutino was provided +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There are (as mKorbel said) a number of ways to do this, but in my personal opinion the easiest way is to subclass JPanel and override paintComponent to draw the image directly into the panel. Once you've done that all the rest of using the window (layout manager, adding conponents) etc is just the same as for a standard JFrame - it's a "set it and forget it" solution.
All you need is to subclass Jpanel, set an instance as your contentPane, load your image into an Image object,and in your subclass include

void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, this); 
}

If you want to re-size the image to fit the frame or anything like that it's just a couple of extra lines of code (hint: image.getScaledInstance(...) ).

mKorbel commented: for resize !0 but getWidht / getHeight +11
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The problem is most likely in the code where you call the individual animation methods. Can you post that code as well?
What thread do you run those calls on? If it's in an actionPerformed or anything like that you have blocked the Swing Event Dispatch Thread (EDT) - Google for more info

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Rather than overriding paint, you;ll be on easier ground by creating a gridlayout of JLabels and using ImageIcon to place your graphics in the JLabels. (just Google it)
If you must override paint then don't re-load the images from disk every time paint is called. It can get called very frequently and all that repeated IO will grind your GUI to snails-pace. Load them all into memory once when the program starts.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

... does that not mean that in more sophisticated programs there would be hundreds of classes, making it pretty unorganised?

Yes there will be hundreds of classes, but no. that's not necessarily unorganised, especially compared to the alternative of having all that code but not organised into classes. OO isn't perfect, but it's the best we've got.

Also, not every noun in the spec needs a class - many of them will create an attribute (variable) within a class. It sounds vague, but when you actually do it a couple of times it's not that hard to guess which nouns are classes and which are just attributes. For big applications you also spend a lot of time reviewing the class design and manually running through the messaging sequences for the use cases. This gives yhou plenty of opportunity to refine the class design before writing any code.

zeroliken commented: great explanation +8
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you start the player playing in its own thread, as correctly advised by cOrRuPtG3n3t!x, then I see no reason why you can't just call ap.stop() directly from the Swing thread (eg in a button's action listener) - no need for flag variables etc. (If you can't call stop() from a thread other than the one where play() was called, then it has no possible use!)

DavidKroukamp commented: True, Old wise man :P +8
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Layout managers are pretty fickle about using or ignoring your component's sizes. You could try setMinimumSize for your panel as well as setSize.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In theory it uses the locale of the machine where it is running - but in practice that's often US for some reason.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Ditto. Maybe you're creating something for each connection or transaction and failing to null all the references to it/them (eg adding them to a List that's not cleared).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It doesn't help that there is no single universal definition of OOP, but I would say that if you just have static methods and don't declare any classes (other than the one the main method is in) and never use the "new" keyword, then your code has nothing "Object Oriented" about it.
Just to be safe, you should restrict yourself to primitive types (int, char etc) because these, by definition, are not Objects. I wouldn't worry about arrays - every non-OO language from C upwards has arrays, so I don't think they are necessarily "objects".

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

.class files are the compiled "executables" that can be executed by any Java Virtual Machion (like a .exe can be executed by an i86 machine). You package all the .class files for your application, along with any other resources it needs, into a "jar" - basically a zip file with a manifest file that describes its contents. If you have a JVM installed on your machine you can run the program in by simply double clicking the .jar file.
In Eclipse select your project, click "export..." from the File menu, then select Java/Runnable Jar File as the export type. You;ll get a wizard that collects the necessary info and creates the jar.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I can't read the text in the attachments, but anyway...
XML is the generalised markup language - HTML is one form/subset of XML. There's all the info you could possibly want on the web, at every level from complete noob to ultimate expert, so I'm not going to try to add to that.
Mime types are a system-independent way to identify file types (eg text, graphics/jpeg) etc. They map to file extensions in Windows. They are used in web browsers/HTML in preference to windows file extensions because they are system independent. Once again, it's all on the web.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The main problem with shared variables is that when classA changes a value, classB doesn't know that it's changed. In your original code you had a loop that just kept re-reading the variable, but that's not something you can do in real life.

In real life you would chose one class to be the "owner" of the data. That class would have the variables private, and have public get/set methods for them.
When you instantiate the other classes you pass a ref to the "owner" class to they can call its get/set methods.
Finally, you implement a "listener" pattern in the owner class. This is just like all the event listeners in Swing - classB implements a callback method, and add itself as a listener to the owner class. As part of the set method, the owner class calls back all its listeners to let them know the new value.

Maybe that's all too much for this exercise, but if you are looking towards real-life techniques, I can supply more details and some useful code fragments.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If the user input 5 you print the 5, then subtract 1, then print the result (4), then subtract another 1 and print 3 etc... until you get down to 0

You;ll have to write the code yourself - but here's an outline of what you need:

ask the user for a number
input the number from the user
while the number is greater than or equal to zero
   print the number
   subtract one from the number

or you could just cheat and copy the code that someone posted without any attempt to explain or teach.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

To use instance variables from another class you need an instance of that class, eg

Point p = new Point(); // an instance of a point (x,y coordinates)
p.x // the x instance variable for Point p

To use static variables from another class you don't need an instance, just the class name, eg

Color.red // the public static variable red from the Color class
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

i get what you're saying. This is what i'm trying to do. The first while loop should read all nums in the array from the left to the right and stop where the element is supposed to be inserted. The condition should be that index < numElements and number is smaller than values. The second loop should start at num elements. and do list = list until the place where it has to insert the value. Then the new number has to be put in. I cant seem to get my loops to do that. The loops aren't nested. I cant seen to figure out how to do this. Any help would be greatly appreciated.

Just try to do this one step at at a time - so first just write the code to "read all nums in the array from the left to the right and stop where the element is supposed to be inserted". In your code print the value to insert, the values in the array and the value of the index variable. Do this both inside the loop and after the loop so you can see exactly what is happening. Maybe it won't work first time, but with those printouts you should be able to see what's going wrong and fix it fairly quickly.

When, and only when that is working, use exactly the same technique to add the second loop and debug it.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's called teamwork. :)

ps Torf: While we're at it, if (x == 1) It's always dangerous to rely on an exact equals with a floating-point value. You can never be certain that x isn't 0.99999999999 after a calculation whose exact result should be 1.0. It's particularly dangerous in this case because you are relying on it to terminate a recursive algorithm. Far far safer to code that as if (x <= 1)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you want to use classes like JOptionPane from the javax.swing package then either
1. Use its fully qualified name javax.swing.JOptionPane or
2. import the class (or package) at the beginning of your program so you can use the class name without qualification

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, you can use Runtime.exec to run a program or batch file, but it's limited in how you can configure the environment for your program/batch.
ProcessBuilder was introduced in Java 1.5 specifically to address the limitations of Runtime.exec and is the preferred choice for all new code.
Currently the legacy implementation of Runtime.exec has been scrapped, and now it's just a cover for ProcessBuilder anyway... here's the Java 1.7 API source code for Runtime.exec:

public Process exec(String[] cmdarray, String[] envp, File dir)
        throws IOException {
        return new ProcessBuilder(cmdarray)
            .environment(envp)
            .directory(dir)
            .start();

See also https://sites.google.com/site/javaerrorsandsolutions/home/processbuilder

DavidKroukamp commented: Hmm very nice +7
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  
   while (...
     ...
     Thread.sleep(...

You simply can't do that in Swing, or rather you can, but it doesn't work.
Everything to do with Swing (eg painting the screen, running actionPerformed methods) happens on a single thread - the "Event Dispatch Thread", or "EDT", or "Swing thread".
That means that once your actionPerformed method starts NOTHING else will happen in Swing, including no screen updates, until your method finishes. You can update stuff and loop and sleep as much as you like, but none of that will affect what's on the screen until your method has terminated.
If you want to do stuff in steps over a period of time the this is the right way:
In your actionPerformed start a javax.swing.Timer, and return. Every time the timer fires you can update whatever needs updating and return. Inbetween the timer firings Swing will be free to update the screen.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You would normally use the classloader's getResourceAsStream method - which has the advantage of immediately giving you an open InputStream on the file in the current jar. You'll find the doc in the usual places, but briefly:
in the code of a class that was loaded from the same jar...

InputStream in = this.getClass().getResourceAsStream("/myTextFile.txt");

If the file is in a folder within the jar then that would be "/myDirectory/myTextFile.txt" When developing your code this also works outside a jar - as long as the file is in the same place relative to where the .class file was loaded from.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Around lines 60 and 228 the initialisation loops stop one short, and leave the last element of each array null.

for(int i=0; i < 12; i++) { // initialises the first 12 elements of 13
   rankArray[i] = new Rank(i);
for(int i=0; i < 3; i++) {        // initialises the first 3 elements of 4
  suitArray[i] = new Suit(i);

I think stultuske was wrong in this individual case. The problem is not that you were accessing non-existant array elements, it's just that you failed to inialise them all earlier.
With 13 ranks and 4 suits your loops should all look like these:

for (int rank=0; rank < 13; rank++) ...
for (int suit=0; suit < 4; suit++) ...
Goldfinch commented: Your solution worked beautifully +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You just need to cast the Object that's returned. String isn't a primitive so there's no boxing involved
String s = (String) btn.getClientProperty ("myString");

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You may need to let the layout manager know that you need it to update the layout after you have added the buttons - try calling invalidate() on your panel after adding the buttons.
The other thing is that icons on jLables and jButtons are notorious because if there is any problem with the icon file name/path etc you get no errors or exceptions, you just get a blank label/button.
Use the exists() method of the File class with the path/name of the file to confirm that your program can find eachfile.

Skeldave commented: Very helpful person +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

new GroceryList(); looks for a constructor with no parameters, but the only constructor you have defined is
public GroceryList(String name, int quantity, double unitPrice)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
static String test=null;
public Card() {
 setValue();//if we dont call this our value wont be set
}  
public static void setValue() {//set value
 test="of";
}

Why such ridiculous contortions? Why not just

static String test="of";
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I think he's talking about Steganography
http://en.wikipedia.org/wiki/Steganography

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

For general data you could use an ordinary zip file
http://java.sun.com/developer/technicalArticles/Programming/compression/

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

By matching the number and types of the parameters in the call to those in the constructor's definition (just like any overloaded method call)

stultuske commented: beaten by the punch :) +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Something like:
When the user selects the first operator that is the first node. When the use puts something in the ... to its left, that becomes the left sub-node of that node, similarly for the right ...
If one of those sub-nodes is another operator then that's a new node with its own left and right sub-nodes.

Maybe you just need to start coding something - eg just entering (a AND b) (no recursion needed here) then what you learn from doing that will help you towards the next step.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I did explain the two better ways when I replied to your other post. Did you read that?

Anyway, here's a new complete answer:

Synchronizing data between 2 classes
You have some data in object1 (an instance of Class1) that changes from time to time. You want object2 to use the latest data from object1. Eg Object1 gets data from incoming internet connections, object2 displays it in a GUI

1. The Worst way: Have loop or timer in object2 that checks object1 at regular intervals - either it's laggy or it's a resource hog.

2. A better way: write a public method in Class2 that accepts new data as a parameter and updates itself accordingly. Pass a reference to object2 into object1 and use that to call the public method. This is efficient and lag-free, but involves tangling the objects together more than is desirable.

3. The best way: Implement a Listener pattern in Class2 to allow other objects to register as listeners. When new data comes in, call all the registered listeners passing the new data. When setting up object1 add it as a listener to object2. This is better architecture (eg it's used throughout Swing), but more code. Depending on how "serious" the app solution 2 may be good enough.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

@Hypnos:
You don't need any parameters for the move method - each object knows its own position (x,y) already. You just need to call move at regular intervals and let each object update its own x and y accordingly.

(just saw your post):
By "speed" I mean the amount by which x (or y) changes each time move is called, so if x starts as 0 and speed is 5, then as move is called each time x will go 0, 5, 10, 15... and thus move across the screen.
Direction is a combination of how much you change x and y each move, eg change x by 0, y by -10, object will move upwards.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"NOT ( ( b ) AND ( a )) ... This formula is terminated has AND is the root"

Are you sure? I would expect the resulting tree to look like this:

NOT
                /   \
               /     \
            (null)   AND
                    /   \
                   /     \
                  a       b
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's right. It's messy, but $ is a special char in a RegEx and needs to be escaped with a \. But \ is a special char in Java string literal, and needs to be escaped with a second \. So to get a literal $ in a RegEx you need the Java string literal "\\$"

DavidKroukamp commented: gr* extra info, i jus tried \\ :) +6
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, joking aside...
If you want to know "how ThreadPoolExecutor can be used to achieve my goal" then the tutorials (as opposed to the sample code) on the web are what you need. It's unlikely that anyone here is going to write a better one for this Thread.
When you say "I want to know how a thread is implemented and thread pool in implemented" what are you asking? Do you want to know about the internal mechanisms of Java threading (not easy) or just how you can implement (a) a simple thread and (b) a simple thread pool (easy)?