JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java variables must be initialize when you use them.
String name = ""; etc etc

They must be initialised before you use their value, but that does not mean that they must be, or should be, initialised when you declare them. Initialising like that is only useful when there is a specific initial or default value for the variable. In the case of this code each variable is assigned a value before it is used, so initialising them in the declarations is a complete waste of time.
In fact initialising in the declaration can be counter-productive because it effectively disables the compiler's checking for correct initialisation. It's far better not to initialise (except for known initial or default values) so the compiler can check your logic.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The parameter is passed directly to your main method from whatever command prompt or IDE has started your program. This link shows how to pass and use such a parameter in netbeans.
ps This is yet another good example of why most of us advise beginners to stay with an editor and command prompt at first. An IDE just adds another layer of complexity and learning curve.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

SwingWorker makes your life easier by linking the process to the GUI update in one place then doing all the complex thread-related stuff for you. But that also means it's a fair criticism to say that this one place violates the separation of GUI and model. That makes me uneasy too, but I guess that's a personal preference.

In my code I prefer to use Observer so there is no knowledge of the GUI in the model itself. I'm a bit of a purist like that. Here is some relevant reading (!)
http://www.vogella.com/articles/DesignPatternObserver/article.html

In its very simplest form you add something like this to your process class

private ChangeListener listener = null;

public void addChangeListener(ChangeListener listener) {
   // just supports one listener to keep this really simple
   this.listener = listener;
}

void notifyChangeListener() {
   // call this whenever data is changed
   if (listener != null) 
      listener.stateChanged(new ChangeEvent(this));
   }
}

Then in the GUI somewhere you implement the ChangeListener interface (ie the public stateChanged method) and add the GUI instance to the process instance by calling its addChangeListener(this); Now whenever something interesting happens in the process you call notifyChangeListener, and the GUI's stateChanged method can update the GUI.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK.
But please understand how your posts will be read. Can you see the difference between
what code do I write to print the total?
and
how can I decide whether to use println or printf?

Just remember the DaniWeb rule "Do provide evidence of having done some work yourself if posting questions from school or work assignments". If you start by demonstrating that you have thought about it and tried some ideas, then people here will help you.

Anyway, you can use any of the various versions of print, println, printf - it just depends exactly how you would like to see the output formatted. There's no one right answer. Considering where you are on the learning curve probably the simplest solution (println) would be most appropriate.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's what your code is doing at the moment...

iterator1 = ...
iterator2 = ....
while (iterator1.hasNext()) {
    ...
    while (iterator2.hasNext()) {
        ...
    } 
    // after the first pass you have now used up all the elements in iterator2
    // next time round the outer loop iterator2 will still be all used up, so
    // the inner loop will never be excuted again
}

... and here's what it should be doing...

iterator1 = ...
while (iterator1.hasNext()) {
    ...
    iterator2 = ....
    // every time you go round the outer loop you need to start a 
    // new iterator for the inner loop    
    while (iterator2.hasNext()) {
        ...
    } 
}
jalpesh_007 commented: really useful... +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I dont understand, How am I not throwing an exception?

eg

if (! ans.equals("y") || ans.equals("n")) throw new InputMismatchException("must be y or n");
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

.Throw an error if the input number is less than zero.

You missed this part out. The catch is OK, but you don't throw the exception when the input is wrong.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Would this solution make it possible for the server to await some sort of input from both playing parties before sending out new information?

Yes, no problem. Once you have established the socket connections you open a two-way link between each client and the server so the clients can send to to server, and the server can send info to any of the clients whenever it likes

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Client/server coms via Java internet Sockets really isn't hard - here's a good short tutorial to start with.

A server for synch and gamestate etc is a perfectly reasonable way to go. SQL would be another area of complexity to master, so maybe better left for version 2?

Java language is pretty ordinary stuff in 2012, its the API (class library) that's really huge and takes a long time to get into. Just take it one step at a time, ie don't try to start with comms, GUI,state storage etc all at the same time.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Line 2 syntax is a bit garbled. This is the easy way to do it:
1. Create a DefaultListModel
2. Create the JList using that model
3. Add stuff to the model
4. Clear/add to the model as required

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The equals method is defined in the Object class, so in the API docs you will find it listed in the "inherited methods" section. That version of equals tests for the the objects being exactly the same object (at the same memory address), so that's what you get if a class does not override it like String does.
In your test code you create two StringBuffers. They have similar data but they are two distinct different objects. StringBuffer does not override equals, so it's inherited from Object, and returns false in this case.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

String sql = ("selectfrom class where Time =? and Stage = ? and Teacher = ? ");
String sql = ("select
from class where Stage = ? and Teacher = ? and Time =? ");
All you changed was the order - which has no significance in SQL - so why bother?

The NPE is hardly surprising...
Line 4: java.sql.PreparedStatement st = null;
Lines 5-12: no assignments to st
Line 13: st.setString(1,time);
... but what is surprising is that earlier you said you had no exceptions.

You seem to be thrashing around here, posting contradictory (or at least confusing) info, and not doing any basic debugging with print statements. So that people can help, I suggest you 1. Fix the NPE then 2. add some debug prints the 3. post the latest version of the code along with the exact output it produces (from print statements or printStackTrace). Of course, you are free to accept as little or as much of this advice as you want.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You don't have to put the source code in the jar, so don't!
You do have to put the class files, so there's no way to stop someone looking at the byte codes and trying to reverse-engineer a source version. You can use a tool called an obfuscator to remove all uneccessary info, and mix up the byte codes so they still work the same but it's very difficult to reverse engineer.
Just google Java obfuscator

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry stultuske, but I found your reply very confusing. Once you create an instance of some concrete class that instance can never change its type. A SampleB can be added to a Vector<SampleA> because SampleB is a subclass of SampleA. But nothing is "stripped from the instance", and a SampleB can never be "transformed" into a SampleA. That instance is still a SampleB with all the extra info that a SampleB has.

What's happening here is that the compiler doesn't know at compile time whether any particular element in the Vector is going to be a SampleA, B, or C. All the compiler knows is that all the elements of v are SampleA.
You then try to assign a value from v to a variable of type SampleC. Not all SampleA's are SampleC's, so the types are incompatible.

stultuske commented: nyes, should 've chosen my words much better. probably the reason I never became a teacher :) +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

(to clarify Majestic's post:
== works exactly as the language definition says it should, including for Strings. It tests for two references being equal, ie referring to exacty the same object. However, it doesn't do what beginners sometimes think it does, ie test for two Strings containing the same sequence of characters - that needs the equals method)

Because Strings are immutable the compiler is able to optimise String literals by sharing them.
eg1,2: It creates a "hello" string for the first statement, then re-uses the same string for the second. The == test (tests for being the same object) is true.
eg3,4: Using new String explicitly overrides the compiler's optimisation and forces it to create new String object. Now there are two different String objects, so == is false. (But x.equals(y) is true becuase they both contain the same sequence of characters)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There are lots of people here who will freely give their time to help you become the best Java programmer you can be. There's nobody here who is interested in helping you cheat or doing your homework for you.

DaniWeb Member Rules include:
"Do provide evidence of having done some work yourself if posting questions from school or work assignments"
http://www.daniweb.com/community/rules

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's just how postfix works. O
n line 4 the value of x-- (10) is passed to the met method, then the value of x is decremented. In the method met, the value of the expression x-- (also 10) is evaluated. The parameter x is them decremented, but this is irrelevant because it immedtately goes out of scope. The evaluated value (10) is then returned. Finally back on line 4 that value is assigned to x.

ps rahul - if you are satisfied with an answer / answers to ypur questons please mark the thread "solved" so others fgind it useful as well.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It can be very confusing to talk about var's and object's types, so I'm going to stick to the proper Java terminology. st is a reference variable that can only refer to objects of type Sample1 or any subclass of Sample1.
(Sample2) st creates a reference that can only refer to objects of type Sample2 (or any subclass of Sample2).
At compile time the compiler can't determine whether that will be valid or not, so it's checked at runtime. At runtime it discovers that st is referring to a Sample1, so that is not a valid value for a (Sample2) st reference. Hence the exception.

Without line 14 it discovers that st refers to a Sample2, so the cast is OK.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

st is a copy of s1, which is a ref to a Sample1. You then try to cast that so Sample2, which is invalid.
The relevant rule is that you can cast a subclass to it superclass, but not vice-versa.
This is because every Sample2 is, by definition a Sample1, but not every Sample1 is a Sample2 (all Cats are Animals, but not all Animals are CAts).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

ok so can you edit the above text for me?

No, absolutely not. This is not a "we do your homework for you" service.
We will help you to learn Java, and help you to write your own programs, but you have to put in the effort.
Try to write this yourself. Get as far as you can, then come back here for help on whatever it is that's stopping you.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You're close. All you need to do is to add the new field to the existing visible JFrame - not a button, not a new frame, just the existing one.
Depending on what layout manager you are using you may also need to call pack() afterwards to let the layout manager make space for the new field.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java is not the same as JavaScript. You have posted in the wrong forum.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes please. There's a "mark this thread solved" link at the bottom of the page.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I agree. The wait would be less code, but the button is far better user interface - it puts the user in charge.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You do realise that this is the Java forum? And that Java already comes with APIs that include parsing/converting numbers from/to any arbitrary base?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

getBytes will extract the text bytes from the string - it doesn't know or care about hex. It will give you {'1', '0', 'B' ...
Then you convert each of those and you get 32 integer values each in the range 0-15.
To decode that as 16 integer values each in the range 0-255 you need to use substring to split the string into 16 strings each 2 chars long, then parse those.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You have that error message because you out an executable statement that's not in a method. Executable statements need to be in a method or constructor. That could be main, or any other method that gets called directly or indirectly from main (including constructors).

(Ps: for the experts out there, I'm deliberately ignoring static and instance initialisers as being too advanced to be relevant)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You really should be compiling this code as you go. You may need to add a couple of "stub" methods - ie with the right signature and if necessary returning a dummy value.
If you keep writing code without fixing the errors then when you finally do try to compile you will get an overwhelming cascade of messages and it will be very difficult to see where to start fixing them. Frequesnt compiling keeps you grounded. At your stage of learning I wouldn't write more than a dozen lines without running them through the compiler and fixing them as I go.
I could point out a couple of errors in your code, but there's no point when the compiler will do that anyway.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's a standard problem! Easiest solution is to use substring to take all the characters from the string except the last one.

jalpesh_007 commented: Solved +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

line 34 you initialise aspStr as null, but then on line 37 you try to append text to it. You can't append anything to a null. Initialise it to an empty String ie "" instead.

jalpesh_007 commented: really good suggestion +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

am cramming for an exam tomorrow

Ooops! Probably better to spend your time on a few other topics because you could burn a lot of hours trying to get this one straight.

ps: Anyone else know a good answer to this one? I can't see any sensible way to solve it within all the contraints.

scarletfire commented: thanks, :) but please try and help me, i really need to get this straight as exam is tomorrow and the pattern is always to fill in blocks of code.. :( +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
 public void printBackward(int n)
     ...
     addLast(list1); printBackward(); count --;

Despite the missing parameter that looks like an attempt at recursion to me :)

scarletfire commented: Thanks, that is my attempt at recursion but am clueless on how to solve this.. :( +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The second [0] is the error.
If there was a 2D array then that would be a valid index, eg

int[][] a = {{1,2,3},{4.5.6};
a[1][2] == 6

but because its a 1 D array ( new int[]{0} ) then the second index is invalid.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The {} in this context define a literal array, as in

int a = 1;
int[] b = {1,2,3};
int[][] c = {{1,2,3},{4.5.6}}; // 2x3 "2D" array (array of arrays)

so {{1}} defines a 2D array 1 row, 1 column, containing the single value 1.
{{1}}[0] selects the first element of the first/outer array, ie the array {1}
So
int[][]{{1}}[0] defines a 2D array, selects the first element of the outer array, and thus returns the inner array {1}, which is a valid value for int[] it

(ps I wrote 2D array, but this isn't exactly correct, Java [][] arrays are arrays of arrays. The inner arrays can al be different lengths, so the [][] does not have to be rectangular)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

barramedalb - thank you for your suggestions. Could you please add some more detail to each of those - not solutions, but some specifications so people will know what you mean by "simple vending machine" etc. Thanks.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Pseudo code can be a useful tool for explaining algorithms etc, but by doing that you have still deprived the OP of the chance to learn how to solve the logical problem for themselves. Follow Norm's frequent approach of getting the OP to do it by hand on a piece of paper, then generalise what they just did, before going anywhere near a computer.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Don't worry, you are not violating any rules!
In Eclipse select your project, then export... from the File menu
That displays a "Choose export destination." dialog from which you chose Java/Runable Jar, which takes you (first time) into a new Jar wizard.
YOu can save your jar settings back into your project, so next time you just right-click the jar description and select Create Jar.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I agree with rotten69.
If anyone out there would like to contribute some "how to do it" please start your own thread and I'll link to it here (otherwize this thread will become too big and hard to follow).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

A [][] array is an array of arrrays. First you need to initialise the first/outer array, then you need to initialise the inner/second arrays, although you can do both at once provided all the inner arrays are the same length egint[][] blocklist = new int[6][3]
Your code just initialised the outer array to have no elements - {} - in which case there are no inner arrays at all. If that array is zero length, then any index will be out opf range.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That demo program was worth every minute you spent on it! I was able to run it and reproduce your problem.
If you don't add the ActionListener ast all, so the button has none of your code attached to it in any way, then you still have the problem. So it's nothing to do with the ActionListener. My guess is that it's a focus problem - clicking the button moves the focus.

You are using the default input map, which is the "when focussed" map. Try adding your binding to the WHEN_IN_FOCUSED_WINDOW input map - that fixed it for me.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java Language Spec says:

5.3 Method Invocation Conversion
Method invocation conversion is applied to each argument value in a method
or constructor invocation (§8.8.7.1, §15.9, §15.12): the type of the argument
expression must be converted to the type of the corresponding parameter.
Method invocation contexts allow the use of one of the following:
• an identity conversion (§5.1.1)
• a widening primitive conversion (§5.1.2)
• a widening reference conversion (§5.1.5)
• a boxing conversion (§5.1.7) optionally followed by widening reference
conversion
• an unboxing conversion
...
If the type of the expression cannot be converted to the type of the parameter by
a conversion permitted in a method invocation context, then a compile-time error
occurs.

so a narrowing conversion like double to float is not allowed.

rahul.ch commented: That was very helpful a read thanks James :) +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Multi-Window currency converter.

You have already done some basic Swing programming and can create windows, handle ActionEvents etc. This project will introduce you to Model-View-Controller architecture and the Observer Pattern as used throughout Swing and real-life GUI projects. This is the standard solution for displaying shared data in multiple windows.

Create a multi-window currency converter (US Dollars, Euros, GB Pounds etc) etc. Allow the user to create any number of windows, each displaying in one of the currencies. Each window should display the same value, converted to its appropriate currency. Allow the user to change any of the values in any of the windows, and update all the other windows to keep the values consistent. For extra fun, allow different ways to display the values, eg just as a number or as a JSlider.
You will find that the only sensible solution is to have a shared Money class that supports ChangeListeners, and have all of the windows add themselves as listeners so they know when the values have been updated. You will also need some kind of master controller class/window to manage the whole thing.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I've opened this thread following rotten69's suggestion for "Java projects for beginners".
To get things started I've posted a project in a format that makes sense to me; please feel free to follow that format, or to do it in some completely different style if that seems better.
Let's see how that goes, and when things settle down I'll tidy it up and make it a sticky.
J.

===========================================================================================

This thread is for Java project suggestions.

You have attended the lectures, read the books. watched the videos, but the only way to get good at Java is to write some real programs. These suggestions are for learners at every stage and each one will help develop your skills in one or more aspects of Java. Please feel free to add new project suggestions of your own.

This is NOT the place to discuss detailed solutions, nor to ask for help when you attempt one of these projects. If we allow that in this thread it will rapidly become too large and tangled to be useful. For any kind of discussion about problems or solutions start your own new thread. You can always PM me or another mod to get your thread cross-linked from the corresponding item in this thread.

Special thanks and appreciation are due to rotten69, who suggested this in the first place, and kept pushing until it happened.

anand01 commented: good one james +4
~s.o.s~ commented: +1 indeed +14
Dinesh_9 commented: Yes this is an great way to learn +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi all
I'm perfectly happy to set up a thread for project suggestions, and establish some guidelines to help keep it focussed. I've started a discussion in the moderator's forum to get suggestions there as well. There have been no objections to it, so I will soon start it up and we'll see how it goes. If we get some good input then I'll make it a sticky. Any DaniWeb moderator has the ability to moderate any thread, so it won't be a one-man show, nor will it depend on any one mod being available to keep it clean.
J

rotten69 commented: Glad to hear that there are some positive thought on this matter. +4
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes... except that you still need to reverse the order of the 4 bytes that make up the rightmost 32 bits. ie if we lable the 8 bytes of the long as pqrstuvw then the result you need is wvut (assuming, that is, that I understood all this correctly!)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Since Java does not a 32 bit unsigned data type the "right" answer to this depends on what you want to use it for. Is this for writing/reading compatible files?
If the php version is a 32 bit positive integer then a Java long with the same value will have that value in its last 32 bits, and its first 32 bits will be all zero.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Means what it says. The compiler attempts to check all the paths through your code to make sure you always initialise variables before you try to use their values. It has seen that there are some combinations of the if tests where this may be a problem.
You fix it by ensuring that your variables are always initialised no matter what the results of the if tests may be. The simplest solution is usually to initialise them when you declare them, so they have a "default" value, eg
int x = 0; String s = "";

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I just looks like you need to call countRowI) before you create the array.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Like I said - let's see what opinions everyone has. This is peak holiday season, so we should allow a couple of weeks for people who happen to be away this week. We're talking about maybe building a resource that will be used for years, so let's take a bit of time to get it right.