JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You have made this too hard by building a List of arrays.
It will be much simpler if you just have a List<String> containing one word per entry. So at line 8, instead of adding the whole array to the list, use a small loop to add all the words in the array to the list one at a time.
Now you have a list of words, you can simply use stopList.contains(someWord) to see if someWord is in the list.

ps Line 7 does nothing - toString returns a string representation of the array (its type etc, not its contents), but you don't do anything with that returned value.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java 8 isn't out yet, so you can safely ignore it for now. I just posted that for anyone who was preparing to support Java 8 when it is released.

If you need more help with your assignment, just post your questoins here. Parts 2 and 4 should be easy enough for you. I don't understand what the teacher is asking for in point 3.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Line 12 looks wrong - you need to set the RGB components, not just stuff a single byte into the ARGB int (the byte value will be the blue, but if it's <0 then the AR and G will all be 255 because the sign bit for the byte will be propogated all the way through the int value, if its >=0 the AR and G will be 0, and a zero alpha won't help!).

Update: This post referred to the earlier version of the code - the latest version deals with this problem.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Is that some confusion over the class name and the variable name? You declare a class FlowLayoutManagerTest but then in the main method it looks like FlowLayoutManager is a class and FlowLayoutManagerTest is a variable. The Java convention is for variable names to begin with a lower-case letter, and it would certainly make it easier for everyone to read your code quickly if you stick to the conventions.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can work with setMinimumSize to have a minimum height and width, (and pack(), of course), but that gives you no control over the width or where it will flow onto a new line. setMaximumSize may allow you to force it onto a new line, but the size is in pixels, where the comonents will vary in width according to the fonts used, so it's not very useful.

IMHO FlowLayout is so simplistic that it's basically useless.

Rather than start with "how do I do this with XxxLayout?", start with a sketch of your desired layout, then look at the visual guide to layout managers and pick the one that's closest to the layout you want, using JPanels to create sub-layouts where necessary.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There is the option of setting the layout manager to null and positioning/sizing everything in pixels using setLocation, setSize, orsetBounds. In doing so you sacrifice any hope of portability between different machines with different preferred font sizec etc, so it's usually a very bad idea. Maybe if you were coding for some known device (eg smartphone) with only one size of screen?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Rather than getting the Image's buffer, and having to deal with all he types (as Paul mentions) you could use the PixelGrabber class to get an array of SRGB ints for any or all of any Image, regardless of its internal format. The API doc for PixelGraber also documents the correct way to extract the individual components from the int values.
If you are happy that your Image will always be a BufferedImage then Paul's getRGB is even easier.

cwarn23 commented: Thanks for the great help! +12
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Maybe its a problem with the byte arithmetic? The RGB byte values are unsigned (0 to +255), but Java bytes are signed (-128 to +127). You may need to do some masking (ANDing with hex FF) to stop the first bit being propogated as a sign bit when you convert byte to int or vice-versa?

Eg. consider this simplified case:

        byte x = (byte) 127;
        byte y = (byte) 127; 
        byte z = (byte) (x + y);
        System.out.println(x+" "+y+" "+z);

I bet you expect to 254 in z. But it's -2.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

A bit of a digression, but I've been practicing with the new features in Java 8 (due March), and I have to share this with anyone who's interested...

The following code creates a map of counts for all the unique words (case insensitive) in all the .txt files in a specified folder...

Path dirPath = Paths.get("c://testdata");

Map<String, Long> counts = Files.list(dirPath). // parallel().
    filter(path -> path.toString().toLowerCase().endsWith(".txt")).
    flatMap(path -> bufferedReaderFromPath(path).lines()).
    flatMap(line -> Stream.of(line.split("\\s+"))).
    filter(word -> word.length() > 0).
    map(word -> word.toLowerCase()).
    collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

more amazingly: just uncomment the parallel() call and it will automatically split and run this in a suitable number of parallel threads!

Java 8 is really the biggest thing since 1.5 - maybe even bigger.

ps: bufferedReaderFromPath(path) is just a cover for
BufferedReader(new FileReader(path.toFile()))
but because lambdas can't throw arbitrary Execptions, it needed a wrapper method to deal with any FileNotFoundExceptions

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Happy new year to you and yours as well.
My own experience has been that setting preferred size seems to be ignored most of the time, but setting minimum sizes are more often honoured by the layout managers I happened to use. I didn't keep any records, so I can't confirm the details. It's just a general impression. I'm happy to listen to anyone with any hard data on this. :)

Personally I use GridBagLayout whenever layout really matters.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I totally agree with everything you said in your last paragraph.

setSize is call for when you're not using a layout manager. By default, most layout managers will make your window "big enough" for its contents.

However if you set a minimum sze for your window then if the layout manager comes up with a smaller size it should "round it up" to your specified minimum. You can also set minimum sizes for your JPanels, which may help with some spacing issues.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

pack() fits everything together according to the layout manager(s) and any other constrains you have specified. Until you call it your laying out isn't finished. In particular the setSize for the JFrame will be overridden by the pack, but a setMinimumSize should be honoured.

There's only so much you can do with a simple layout manager like GridLayout - I see you already found the h/v spacing options for the constructor. You can shift the labels right by changing their setHorizontalAlignment to close them up to the entry fields. How important is it in this case to get it "just right" as opposed to "near enough"?

In the end, if you really want total control over spacing etc, while still retaining the resizability and platform independence that a layout manager gives you, you have to go to one of the heavy-duty managers - GridBagLayout or SpringLayout. SpringLayout was designed for use by visual form editors, so GridBagLayout is probably the best option if you are writing the code yourself.

Personally, I find the visual editors useless for anything other than the most simple layouts, and I use GridBagLayout for pretty much everything. The syntax is a bit cumbersome, the learning curve is steep, but IMHO it's worth it in the end if you really want complete control.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You still need to specify appropriate layout managers for the JPanel and its child JPanels. For th JFrame a flow layout is OK - it will place the panels left to right (given enough room). For the panels you ned to specify a layout manager that stacks things vertically - eg GridLayout(0,1) - one column and as many rows as needed, or (0,2) - 2 cols eg for labels & entry fields.

ps don't forget to pack() you JFrame after adding everything.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The simplest way is to use multiple JPanels to organise the groups of controls.

eg Place 3 JPanels in your JFrame, flowing left to right. In the first one add the two checkboxes, in the second add the x,y labels and fields, in the third add the buttons. In each of those three cases the controls are just placed in a vertical stack (2x2 grid for the middle one) centered vertically in their respective JPanels.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You'll have to look at the source files to see how/why you are parsing that blank space - your split method parameter should deal with it automatically.

how can i make my code to neglect certain words which are in an file say stop.txt?

You can read stop.txt into an array (just like reading the words in your existing code). You can then write a tiny method that tells you if a given word is in that array or not, and you can then use that method to decide which words to neglect.

There are classes in the Java API that will make this easier, if you want to learn/use them. Eg read the words in stop.txt into an ArrayList, then you can use its contains method to see if it contains a given word.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

But i am not sure what this {=1 why its getting printed

Looks like your splitting may be returning exactly one empty string, ie "" (or maybe an unprintable character). In the loop starting line 27 you could print the read variable (inside a pair of delimiters so you can see its exact length) to see what's going on

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Lines 38-42 increment the counts for an array of words, so if you execute that code inside the loop, after creating each words array (line 25), that should be OK.
ps It's useless to say "I'm getting errors" if you don't say exactly what those errors are!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Your first loop (17 - 37) processes many files, but stores its results in a "words" array that gets replaced on each pass of the loop. SO after the loop you only have the words array for the last file prcessed.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"words" must still be null - look at the earlier code to see how - use print statements to see exactly what's happening.
ps - I'm going out now, maybe someone else will help
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

After creating the array you need to populate it by assigning new JPanels to each of its elements.
eg

for (int 1 = 0; i<12; i++) jp[i] = new JPanel();
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In your catch block execute an e.printStackTrace(); That will tell you the exact line where the NPE happened, from which it's usually easy to see exactly what went wrong.
Anyway... You already have written code that will read and store all the words from all the text files in a directory (when it's debugged), so this is just a subset of that.
(There's no point trying to add new functionality to a program that's not working yet.)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, so start with number 2 "Read a list of words from a file". You already have written code to read and store all the words from all the text files in a directory, so this is just a subset of that.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Did you really write that code? It displays a wide knowledge of Java syntax, including some of the latest language enhancements. Someone with that kind of programming skill would surely know how to handle parts 2-4.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Post the exact complet etext of your eror messages. Don't expect us to guess what they are.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Glad to help. Please mark this "solved" for our database - you can always start another thread if you have new question.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

jp=new JPanel[12];
creates an array of 12 references to JPanels, but it doesn't create any JPanels, all the references are null, which is why you get the NPE on line 41.
After creating the array you need to populate it by assigning new JPanels to each of its elements.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I don't have time now to study your code - I gave up when I saw you trying to add things to a JLabel! But you can't just add overlapping things to an ordinary frame or panel and have any control over which gets painted on top of which.

But in general there are two ways to have a background image:
1. Create a trivial subclass of JPanel that draws its background from your image file, and add all you other components to that.

class PanelWithBackground extends JPanel {
        ...

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(myBackgroundImage, 0, 0, this);
    }
}
  1. Use a JLayeredPane with a JLabel for the background and use the layered panel's Z ordering to ensure the background label is behind everything else
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It depends...
For primitives that are local variables declared inside methods or other blocks, and for method parameters, they are allocated on the stack and released as soon as they go out of scope.
For primitives that are declared as static members of a class, the lifetime is the same as the program's.
For primitives that are instance members of a class, their lifetime is the same as that of the instance in which they were created.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Where you create them and where you store them are two different things. It may be best for the Game class to have responsibility for creating everything, including Items, but then immediately adding them to the appropriate Inventory.

Coupling is always a bit of a question in respect of the "Master" class that many apps have -in this case your Game class. It typically needs to have access to everything else in the game, so is highy coupled. Whether the coupling from Game to Item is via Inventory or not doesn't look like a big issue here, so personally I'd stick to the structure shown in yor class diagram, at least until I found a reason not to.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's the object-oriented way of thinking! Sudents study Subjects, not "subject names".

Suppose you want to know how many credits a Student can earm from his current set of Subjects - you loop thru his List of Subjects adding their credit points. If all you have is subject names you have to use those to look up the corresponding Subjects in some kind of Map in order to get the credit points.
(Same for checking whether he has met minumum requirements for spread of Subjects, of has forboidden combinations of Subjects, etc etc.)

It's not "heavy". Either way the Student class just has a list of refernces to other objects, be they Strings or Subjects

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In that case I would ensure that Student and Subjst follow the rules for JavaBeans, and use XMLEncoder to write the ArrayLists of Students and Subjects to a file in XML format. You can use any extension for the file you like. (I have done this myself, it really is simple.)

To be fair: Others may still prefer to use SQL to store the Students, Subjects, and the Student/Subject pairs. Its certainly do-able, but a lot more code than XMLEncoder. If any SQL enthusiasts out there want to make the case for doing that, now would be a good time...

Maybe you should use a custom TableModel that' simply a wrapper for the data that's in the two ArrayLists - then there's nothing more to store for that.

ps Why do the Student objects store subject names, why not Subject instances?

CoilFyzx commented: I am now at the point where I am creating a 'wrapper'for the data via a custom TableModel. This is all alien to me. Are there any resources available to guide me in the right direction please? +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The system classpath variables contains a list of places where Java will look to find classes. The jar should be in a folder referred to in the classpath so Java can find it. See http://download.java.net/jdk7u6/docs/technotes/tools/solaris/classpath.html for more info on classpath - that link's specific to solaris, but the same principle applies to Windows. You can Google for more examples and tutorials

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"What sort of info" was a summary of your question, followed immediatly by an attempt at an answer (classes & methods etc) - I wasn't re-asking it back to you :)

The problem here is that there are many quirky details about how to select and implement the various examples of persistence in your question. Apparently tiny details in the requirements can swing the choice one way or another. Within the time/resource constraints of a volunteer service like this there's only so much time we can spend. To give an answer noticibly better than the one I already gave I would need to understand the whole picture (complete requirements specification, use cases, technical constraints, success citeria, financial/timscale constraints etc etc.), and complete a first-pass design.

That's obviously unrealistic, so I was suggesting that you should take what's useful from the suggestions from this thread and attempt the first-pass class diagram, which would be a good basic for further review and discussion.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

To use that jar from an ordinary Java application (ie not in Eclipse) you should place a copy of it somewhere in the system classpath

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

What sort of info? I woul;d start by trying to name all the main classes that will represent the data and all the things you want to do with it (ignore the GUI for now). Write the names, return types and parameters for the main public methods you will need to call. Now, on paper or even just in your head, try to run through a few typical use cases using those classes and methods. Keep refining them until the use cases work smoothly.
Then, and only then, code all that up in Java along with some simple test methods to conform that your code works as expected.

You will inevitably need to add to those classes (eg to support the GUI) and maybe re-write bits when you run into problems. That's OK. The main thing is to develop one piece at a time and keep testing as you go.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

it is processed to create data that does not belong in the database. So I have to save that data locally,

In that case I'd go back to just serialising or XMLing the highest-level Java object (ArrayList or whatever) that holds all that data, but I'd be sure to implement that via an interface so I could change it later.

Can't comment on the last question without a LOT more info. Maybe jsut start with something simple an go from there???

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There is a problem that, from tine to time, Oracle change the serialisation format for one or more classes - in the Image case I mentioned before it was to close a security loophole. That's why its only really safe for transient storage or data transfer. A file written before the change may not be readable after the change. In practice this is a rare event, and you may never encounter it if you are just using serialisation to hold status info from one run to the next.

If the data came from a database in the first place, then maybe it's not necessary to save another copy - all you need to save is anything changed but not yet comitted to the database, or additional status info that's not part of the actual data (eg window sizes).

Without more understanding of your application it's hard to be specific. My instinct (and that's all it is) leans towards:

  • data should be updated back into the source database
  • credentials and preferences should use the java.util.prefs.Preferences class
  • session info like window configuration should be saved in an XML file

... but without knowing the full requirements this is just a provisional opinion.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Serialization allowes you to write/read arbitrary objects to a binary file, in a Java-specific binary format that may be subject to change (not just an empty threat - I had a live system fail when the serialisation of Image objects changed somewhere in the later releases of 1.6).
A very similar alternative is to use the XMLEncoder/Decoder classes to write the objects to a .xml file in standard XML format. It's much the same as serialising, excepy that you have a readable standard XML format file, not an obscure proprietary binary file.

Re GUI objects - you can't serialise open WIndows etc because they are tied in to native OS components - you would have to create a little class to hold the types of the open windows with their x,y coordinates and sizes, from which you could easily reconstruct the user's visual layout.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In defence of cool_zephy's suggestion...
Storing a Serializable object - no matter how complex its internal structure and content - is a single call to writeObject. Restoring it ditto.
Storing/restoring data with multiple occurences of complex data by mapping it into relational tables can be very complex and code intensive.
I'm not saying that using a database mnager is a bad idea, just that writing a currentState object to an ObjectOutputStream could be vastly simpler.
Personally I would
1. Start with making my state object a valid javabean, then use java.beans.XMLEncoder to write it as an XML file
2. Encapsulate the whole save/restore behind a simple interface so I could change ithe implemenattaion later.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I guarantee that nobody human can possibly tell you what's wrong with your code if you don't show us that code!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can append any String to a StringBuffer by using its append method, eg

StringBuffer sb = new StringBuffer("pattern is ");
String pattern = "/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/"; // will need to escape the \ chars as \
sb.append(pattern);

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Where exactly did you see them?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Blue button "Mark Question Solved" about 12 cm straight down from the word "Blue" in this post :)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If that solved yoyur question, please mark this "solved" for our knowledge base.
Thanks

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If that solved yoyur question, please mark this "solved" for our knowledge base.
Thanks

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Like I said - the Checkout needs a reference to the real Index so it can call its getVal() method. Normally that happens in the main code that opens all those windows, maybe something a bit like this:

Index theIndex = new Index(); 
...
// then when the checkout window is opened
// pass theIndex as a parameter to its constructor
Checkout theCheckout = new Checkout(theIndex);

... but the details of your will of course be different

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I think the eror handling exception is not the real problem here - it's addressing the symptom, not the cause. The String is null becuase of an error in the code structure (see my previous post) - fix that and the exception will never be thrown

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In Checkout you create a new Index then immediately get LCNum from it. At that point the user has had no chance to interact with that Index, so its value1 has never been set, so it's null, which is why you get that SQlerror (phew!).

The fix for this lies in the code that manages these separate parts - which wasn't posted, so it's hard to say any more, but basically you need to get a reference to the "real" Index instance, and pass that to Checkout so it can query value1 correctly.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK. Just FYI here's the simpler algorithm - I didn't encapsulate it in a method because it's only one line...

        System.out.print("Enter three points for a triangle: ");
        Scanner in = new Scanner(System.in);
        Point a = new Point(in.nextInt(),in.nextInt()); // eg 10 10
        Point b = new Point(in.nextInt(),in.nextInt()); // eg 10 110
        Point c = new Point(in.nextInt(),in.nextInt()); // eg 110 10
        int area = Math.abs(((a.x - c.x)*(b.y - a.y) - (a.x-b.x)*(c.y-a.y))/2);
        System.out.println(area);  // should be 100 * 100 /2 with above data
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's one way to do it.

A more experienced programmer would probably separate the user interface from the calculation.
The initialisations on line 7-9 are redundant because those values are never used.
There's a much simpler formula for the area of a triangle defined by three Points a,b,c:
0.5*((a.x - c.x) * (b.y - a.y) - (a.x-b.x) * (c.y-a.y))