JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In general: if you hide your internal implementation behind gettersthen you can change the implementation without breaking any other code that uses your class. Ways in which you might change include:
Changing the private data type (eg Date to Calendar)
Waiting until someone requests a value before creating it (eg if it needs a database access).
Implementing security rules.

Setters also allow you to change the data types, but also ensure that you always know when the value changes - maybe this has effects on other things that will never get processed if the user can just change the value without you knowing. Eg
You need to update a dataabse when the value changes
You need to apply access control rules to the update
You need to recompute the sales tax if the price changes
You need to change the shipping rates if someones address is changed... etc etc

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

chaospie:
What you say is basically right, but it hides an important point that can confuse learners. You cabnnot "cast an object". An Object's class is unalterable. What you are casting is the reference. Ie you are saying "this ref to an Object is really a ref to Cat". The object iteself was, and always will be a Cat.

NewOrder commented: Thanks for the (Cat)animal[i] explanation +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Your mask should print as ".*\.txt" -- you should only see the double backslash when entering a Java String literal. You have doubled the backslashes once too many in line 6, which should be replace(".", "\\.");

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi jon. The dir param isn't relevant to the problem as stated - he just wants to filter by file name regardless of directory.
the aragex(..) method certainly looks odd; is it intended to return a result or set a local variable, or both (in which case why?). And we have no evidence that this particular FilenameFilter is even being used at all...
hence my "try debugging it" suggestion.
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

How about some basic debugging? after line 12 print the name and the strRegex to see if they are both what you expected.
ps does this mean that yesterdays dangling metachar thread is now "solved"?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

ps: here's a good example of how the right architecture can help you...
combining the word/number thing into the code I just posted is easy because of the way it's structured...
Inthe Phrase class you implement the abstract method like this

class Phrase {
  Superclass newLowerClassInstance(String params) {
    Word w = new Word(params);
    if (w.isAllNumeric()) return new NumericWord(w);
    // Word class needs a method to say it consists of all numerics
    return w;
  }
}

class NumericWord extends Word{
   NumericWord(Word w) {
     // copy the instance variables from w
   }
}
ankilosado commented: JamesCherrill, thanks for your effort in getting into my shoes, and for putting your knowledge at my fingertips. You took your time to carefully understand my problema and got it seriously to help. +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No, it's not the only way, but it's the way that people use 99% of the time. You will find some excellent tutorials on the web for using Java with a database. I recommend this one:
http://download.oracle.com/javase/tutorial/jdbc/index.html
It's quite a lot to understand and learn, but its an essential basic skill for real-world commercial Java work, so its worth the effort. Good luck!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Source: JDK 6 API http://download.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html
String's split method will return what you want:

String s = "13866,Stephen Moran,Stephen Moran,Killaroo,Streamstown,Westmeath,Ireland,,Moran ,2010-08-05 00:00:00,0,0,,,0,O4,Moran_013866";
String[] tokens = s.split(",");
System.out.println(tokens.length);

>> 17, and is NOT "discouraged"

EDIT: parallel post with previous update. Why "messy" if you were going to put them in an array anyway?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Is there any special reason to use an array for statistics? This kind of tree-like structure fits very badly in arrays. Why not just add them to the class itself? This is a much more "object oriented" way of thinking. So in each class you have public getter methods like (for the Page class)

public int getParagraphCount() {
   return paragraphList.size();
}
public int getSentenceCount() {
  int n = 0;
  for (Paragraph p : paragraphList) {
    n += p.getSentenceCount();
  }
  return n;
}

Now you can access anything by a very natural for-each loop using the objects themselves, rather than trying to compute and understand array indexes.

It's usually better prectice to get statistics like this "on the fly" rather than calculating them and storing them, if the overhead isn't large. This way they are guaranteed to always be up-to-date.

As for saving the parsed data, why nor just declare the classes as Serialisable and write the top Document instance to am Object file?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Have a public method in the first class that accepts the object array as a parameter.
Pass the first window as a parameter to teh constructor of the second window.
When the user clicks OK you can then call the method in the first window to return the data.

Edit: Thanks norm: ... unless you need the first window to be blocked until the second is complete, in which case use norm's solution
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's the right way to decrement by 10. Just move it to a line after you use it, not before. ie

TwoDArray [j] = k;
k = k-10; ( or k -= 10; - shorter but ewaxctly the same)

Xufyan commented: thanks +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Norm is right - the word in bold should not be there.
And don't worry - your English is good enough. A lot better then my ... Spanish?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

20 seconds with the Java API reference would have lead you immediately to the following statement in the doc for contains:

Note that this method is identical in functionality to containsValue, (which is part of the Map interface in the collections framework).

In fact it was probably quicker to look this up than to create the thread.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I had some more thoughts - feel free to use them or ignore them...
I would separate the messy business of parsing the chars and delimiters from the logic of building the doc structure. Instead of passing a Scanner, I would build a class to do the initial parsing and pass that around instead. It only needs 3 public methods: get next char, get next delimiter, "peek" at next delimiter (ie return the delimiter but leave it on the stack). I'd pass the file name into its constructor so all the choices about scanner vs byte array parsing etc are hidden inside it. That will make all the code easier to understand, allow the parsing to be tested before its used in the doc structure classes, and allows you to change the implementation if you get into difficulties.
I's return the delimiters as int values (1= word delim, 2= phrase delim etc) describing the exact type of delimiter, so you can test for == WORD_DELIM or >= WORD_DELIM - I think you'll need to do both.
Finally, I'd add a writeXLMto(PrintWriter out) method to all the doc classes so I can easily display and debug their contents - eg
word.writeXMLto gives
<Word>Fred</Word>
then you can use that for Phrase to give:
<Phrase>
<Word>Fred</Word>
<Word>Sally</Word>
</Phrase>
etc etc

Let me know how this goes - I'ts caught my interest!
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi ankilosado
Yes, the Scanner knows where its current poosition is, and it's considered better Java style to pass something as a parameter (ie share it in a controlled way) rather than making it public static (ie totally uncontrolled sharing). (When you pass an Object as a parameter what you are really doing is passing a local copy of a reference to the Object, so all the local parameters are references to exactly the same Object.)
As for the double CR problem - I automatically dislike the idea of special-casing this. Won't there be other similar cases? Eg full-stop+space at end of sentance is NOT two word delimiters. I never get to use Scanners myself, so I'm no expert, but can't you use hasNext for a quick look-ahead to see if the next "n" characters match a regex? If so, you can look first for the 2-character delimiters, and only if that fails, look for a single character delimiter.
As for empty elements: is this a gap in the spec? How should it handle consecutive delimeters (eg newPage/newPage - is this an empty page, or should you just ignore it?).
If you wnat top ignore empty elements completely, it's easy enough to chcck them before adding them to the ArrayLists, ie replace

add new Phrase(input) to ArrayList

with

Phrase p =  new Phrase(input);
if (! p.isEmpty()) add p to ArrayList

wher isEmpty() is a trivial method implemented in each class

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's a strategy that may work for you - it's kinda like a recursive strategy, except that the levels are pre-defined. Pseudo code fragments follow:

new Document(Scanner input) {
  create empty ArrayList of Pages
  while (not input.EOF) add new Page(input) to ArrayList
}

new Page(Scanner input) {
  create empty ArrayList of Paragraphs
  while (not input.EOF) {
    if (next token in input is a Page delimiter) return;
    add new Paragraph(input) to ArrayList
  }
}

new Paragraph(Scanner input) {
  create empty ArrayList of Phrases
  while (not input.EOF) {
    if (next token in input is a Paragraph delimiter) return;
    add new Phrase(input) to ArrayList
  }
}

...


new Word(Scanner input) {
  create empty ArrayList of Characters
  while (not input.EOF) {
    if (next token in input is a Word delimiter) return;
    add next Character to ArrayList
  }
}
ankilosado commented: he read my problem and thought about it before answering, which I appreciate a lot. This allowed him to understand my problem. +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes.

This may help you: for each of yopur classes create a public String toString() method (overrides the defaultg useless implementation in Object) that returns a printable representation of the values in that class, then use it to print out the values before & after serialisation.
Every class should have a toString - it's really valuable for every kind of debugging.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Your deserialised object(s) will contain data with the same values as the original objects - but they will not be the actual same data items as were serialised (eg: you may serialise to a file, quit your app, close the JVM, start a new app in a new JVM and deserialise the objects - values will be the same, but the original objects will be long gone).
== tests for two references being references to exactly thwe same object in the JVM's memory, which these are not.
If it's appropriate in your app (eg) for two of your object to be considered equal if they contain the same values, then you need to give them an equals(Object 0) method that compares all the values and returns true or false as appropriate. This is exactly what happens with String objects - the String class has an equals method which returns true if both strings contain exactly the same sequence of characters, even if they happen to be two different String objects in memory.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Forum rules say I can't write your code for you, but here are some hints:
the method header says you will return an object of type Set<Food>
So somewhere in your method you need to declare one, populate it with zero or more Food objects, then return it in the return staement.
I have no idea how we got from characters to Food - what's your REAL question?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

vegetables class doesn't have a variable called length.
Were you thinking of whatever the getFruits() method returns? Sounds like that may be an array? In which case that's what you should be using instead of calling.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can use an ObjectOutputStrem / ObjectInputStream via you sockets to send a set of results. If all the calsses & subclasses are serialisable that simply works. If not, extract the data into something that is serialisable and send those.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Local variables do not get garbage collected. They are allocated on the stack and thus automatically lost when the block is exited (the block in this case being the while {...}). The objects to which the variable refers are not on the stack, and are eligible for GC when there are no longer any (strong) references to them.

Sun says:
14.4.2 Scope of Local Variable Declarations
The scope of a local variable declaration in a block (§14.2) is the rest of the block in which the declaration appear.

Thus the scope of this variable is from line 8 to line 14
Contrary to my over-simplified earlier post, when the execution returns to line 2 as part of the looping, the variable is out of scope, and any reference it may have held is no longer valid.
QED I belive the nulling on line 13 is redundant.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java does support mp3 http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html

For info on how to get the individual samples and do a FFT see
http://jvalentino2.tripod.com/dft/index.html

unbump..

Am I really the only person on this forum who knows how to use Google?

Ezzaral commented: It's a possibility :) +11
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sun's documentation states "The default class path is the current directory".

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java has a Preferences class that's ideal for what you need. It's as easy as

Preferences prefs = Preferences.userRoot().node("myEditor");
prefs.putBoolean("lineWrap", true);
...
if (prefs.getBoolean("lineWrap", false)) ...

UI should be a dialog, and keeping it modal makes coding, and using, it easier.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

At the risk of making a total fool of myself...
I got very excited when I discovered that Java's "only opaque rectangular windows" limitation has been removed. Full release is intended for Java 7, but working methods can be accessed thru com.sun.awt.AWTUtilities in recent releases of Java 6 (I'm using update 20).
I put together this little demo that adds some animation to the effects to give a hint of the potential. It runs for me under Windows 7 Home Premium; I just had to adjust Eclipse's compiler settings to warn rather then error for access rule violations.
I'd be very interested to hear anyone else's experience of these exciting new capabilities.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

import com.sun.awt.AWTUtilities;
@SuppressWarnings("restriction")

public class DemoWindows implements ActionListener {

   public static void main(String[] args) {
      // create a new demo, and update it every 50 mSec
      new Timer(50, new DemoWindows()).start();
   }

   int phase = 0; // demo runs a number of consecutive phases
   int count = 0; // each of which takes a number of timesteps
   
   JFrame window1 = new JFrame("Java windows demo");
   JLabel text1 = new JLabel("<HTML><H1>This is a demo of some of the effects"
         + "<BR>that can be achieved with the new Java"
         + "<BR>transparent window methods</H1>"
         + "<BR>(requires latest version of Java)");
   JFrame window2 = new JFrame("Java windows demo");
   JLabel text2 = new JLabel("<HTML><center>Java<BR>rocks");

   int w, h, r, x, …
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Not sure wht's going on here, but DeadSoul's post (the first one, not the insult) is incomplete. His instrctions give you the .java file, but you need a .class or a .jar to run the program (just like chirag said).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Have a look at the methods that JButton inherits, such as setHorizontalAlignment(...)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry guys - I may be a bit geriatric but I don't need 1/2 inch high lettering just to compensate for the garish colours.
And please reinstate the poster's reputation and solved thread count info on posts - it's the only easy way to see whether that person knows what they are talking about.

jephthah commented: word +0
BestJewSinceJC commented: agreed +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If there's a getHeight() method then there's probably a setHeight(int h) as well.

ttboy04 commented: 1 +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I see no-one has replied to this (wonder why???), so I'll have a go.
Is the following the kind of thing you are looking for?

interface I<T extends Event> {
      T dosomething(T t);
   }
   
   class Event2 extends Event {

      public Event2(Object arg0, int arg1, Object arg2) {
         super(arg0, arg1, arg2);
      }
   }
   
   class C<T extends Event> extends PriorityQueue implements I<T> {

      @Override
      public T dosomething(Event t) {
         // TODO Auto-generated method stub
         return null;
      }
      
   }
    void test() {
       I<Event2> c = new C<Event2>();
       c.dosomething(new Event2(null, 0, null));
    }
kvprajapati commented: Helpful! +9
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

BJSJC: You're looking at sql.date. java.util.Date says
Date()
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

BestJewSinceJC commented: Oops! Thanks! +5
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Google the Java Event Dispatch Thread and read about Swing threads.
Your repaint() calls won't do anything until your event method completes, even if it sleeps in the meantime..

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

you should have kept the declaration that is NOT in the method.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You should create a variable just to use as a synch object then if two pieces of code should not run concurrently, explicity synch them on that same variable. If there are two different situations where that applies you can have two variables (etc). Avoid having to synch on two variables simultaneously (avoids deadlocks). Keep it simple, keep it explicit. eg

Object dirLock = new Object(); // just for synching
...
synchronized(dirLock) {
   // mkdir code
}
...
synchronized(dirLock) {
   // chdir code
}

just don't call either fo these pieces of code from within the other!

musthafa.aj commented: clear +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

sorry james can you send the solution with mouse event....

#O already did. It's the first code sample in post #92
Those are the methods for the mouse and keyboard listeners.

kvprajapati commented: Good stuff! James. +7
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, the first frame is always going to be a big hit, and a colourful background is going to kill the GIF/PNG type compressions that you need for text etc. A 1280*1024 24 bit colour image is 3840k of raw data, so 3380k isn't surprising. For certain, replacing the background picture with a solid colour will give a big improvement. You're right - that IS why commercial products like to grey out the background. Maybe, just for the very first screen, it would be better to revert to the PNG version, then switch to my differential RLE thereafter???
musthafa's code (which I don't really understand) uses JPEG, which will be good for the background picture, but horrible for text - I think JPEG is not appropriate.

musthafa.aj commented: good effort!!! +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, this is based on your idea of pixel change, but instead of transparency I just send a code of how many pixels to leave unchanged. The (current) comments from the code may help...

// Output stream format is sequence of 1 integer records describing the
// data array in natural order (element 0 ... data.length-1)
//
// Unchanged record (sequence of >=1 unchanged pixels):
// bit 0 is 1,
// bits 8-31 are number of consecutive unchanged pixels.
//
// Changed record (sequence of >=1 identical changed pixels):
// bit 0 is 0,
// bits 1-7 are number of consecutive pixels the same,
// bits 8-31 are the 3 byte RGB values for these pixels.

musthafa.aj commented: effort!!!! +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you are using my RLE compressor, that was written assuming that the Alpha value was not being used - so it uses that byte to hold repeat counts, and forces it back to Alpha = 255 (100%) when decompressing. Obviously that's not going to work if you want to send transparent pixels and keep their transparency!
I have an idea for incorporating the changed/unchanged info in my RLE compressor that may just work very well. I'll try to do some work on it, but I'm a bit busy at the moment. I'll get back to you when I get a chance.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Line 3 you confuse q and i.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi guys.
Don't know why yu get these delays - I'm seeing 200mSec to scan the whole screen and then just the transmission delays for a few changed cells (64*64*4 bytes each, less 30% for RLE compression) = 11k/changed cell.
Across a WiFi link with a 2-second refresh rate it's almost like watching the source screen, and server CPU is < 10%.
I've stuffed the code together with just enough context/infrastructure to run (I'm doing this within quite a large context, all of which is irrelevant here).
The zip contains a server jar and a viewer jar.
The server has no UI, and exits when the client disconnects. If you can't connect in the first place you'll have to crash it from taskmanger or whatever.
The client attempts to re-connect to a server at whatever address it previously found it, and prompts for a host name / IP address if it can't connect (eg first time run).
Let's see how that works for you!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In case anyone's still interested in this, I tried a few things and got the best result by dividing the screen into 16x16 equal rectanges and only sending the ones that changed. After some optimisation I got down to 1/5 second (200 mSec) to scan the whole screen and identify the changed tiles. I send that data as an array of raw integers (RGB) via a buffered data stream - giving a round-trip elapsed time of just over 1 sec (LAN) for a complete screen (first time only!), reducing linearly to zero with the number of changed rectangles. I used a grid ot JLabels to display the screen at the client, thius avoiding having to merge the changed rectangles myself. I can share the critical code if this is still a live issue for anyone.
Peace.
J

KirkPatrick commented: You sir, have a brilliant mind. I was following this thread because the knowledge between you guys intrigued me. Nice to see you found a good solution. +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Looking better: you still don't need things like companyName (use the inherited name variable) or depositRate(use the inherited rate variable) or the accessor methods for these vairables (use the inherited accessors).
Get/set name for Accounts doesn't make sense. It's Customers that have names.
Deposit doesn't need a customer parameter - you already know the customer for this account, ditto balance, rate, and name in the next 2 methods.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

A few quick observations:
Class names: should begin with a capital letter and shouldn't be plural when they represent a single instance of something. Eg use Account rather than accounts.
An Account is not a kind of Customer, so it shouldn't extend that class.
Do you need personName and companyName? Why not just use the inherited name variable from Customer?
The no-args constructor for Customer (etc) is dangerous - it allows the creation of a Customer with no name, and therefore no way to refer to it or find it later. (Typically you would have a unique customerID field that is mandatory in all the constructors.)
Customer and Account should be abstract - you cannot instantiate one of there, only their concrete sub-classes.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi javaAddict: I hadn't realised that you were already dealing with mseck's problem. (And, once again, I apologise for my "senior moment" with the + , even worse now I've read the previous thread!).
I gonna bow out now, before I make a bigger fool of myself.

verruckt24 commented: I guess thats okay considering your posts are typically very helpful :) +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You stop() before you deal with the pong. Using stop() is a bad idea. It's deprecated. Set your threadcontinue var to false to exit the run cleanly.
Anyway - if the first readline isn't ping then you do a second readline to check for pong. That's one readline to many, and the cause of your problem.
Finally
while(threadcontinue==true) {
is redundant, just use
while(threadcontinue) {

Olliepop commented: Thank you very much +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

i want to add source files that i made in another computer to my project.
i want them to be at the same folder as the project.
how do i add them to the project?
(to copy them into the folder wont help in this case..)

thx!!

Right-click the package where you want to add the files and select "import"

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You declared the variables in Tile as static!

tux4life commented: Exactly! +6
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I want to pass all the values from a HashMap to ArrayList

HashMap has a values() method that returns a Collection of all the values.
ArrayList has a constructor that takes a Collection of values to populate the list. So all you need is a single line of code.

anilopo commented: thx! +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There's too much missing code to tell - but it looks like you may be reading the two objects in two separate threads each of which opens the inputstream? If so, try reading both objects together, just like they were written. I can confirm that ArrayLists of Objects transfer via writeObject/readObject just fine (provided the contents are serialisable).
Why are you using writeUnshared rather than a normal writeObject?