/*** i wrote it for fun! ***/
String txt = "the text"+'\n'+"has three lines and four four_char words."+'\n'+"can you find them all?";
// lets read the second line of the text;
// set a pointer;
int p = 0;
// find the first line break;
int i = txt.indexOf('\n',p);
// increment the pointer;
p = i + 1;
// find the second line break;
int j = txt.indexOf('\n',p);
// count how many four-letter words were read;
int counter = 0;
p = i; // reset the pointer defined before;
for (int k = i+1; k<j+1; k++)
{
char c = txt.charAt(k); // get a buffer character;
if (c == '\n') // if End_of_Line;
{
int charkount = k - p; // count how many characters in this word;
if (charkount == 5) counter++; // a four-letter word is found, so increment the counter;
break; // exit the loop;
}
else
{
boolean b = isWhitespace(c);
if (b) // if this is a white space;
{
int charkount = k-p;
if (charkount == 5)
{
counter++;
continue; // continue the loop;
}
else // if this is not a white space;
{
p = k; // reset the pointer so that it indicates where the new word will start;
}
}
}
>
amishslayer:
personally, i think you are mocking me. however, if you give me your homework to do, i dont mind! at the end of the day, i have nothing to lose. and i will do it as an exercise. probably i can learn more from doing it.
so if you still want to mock me, give me the assignment topic then. but dont make it too difficult to me, because i am still a college student. (umm, i will go to a uni. this Sep.)
> amishslayer:
>
> personally, i think you are mocking me.
> however, if you give me your homework to do, i
> dont mind! at the end of the day, i have nothing to
> lose. and i will do it as an exercise. probably i
> can learn more from doing it.
And the person you "helped" gains nothing as well... perhaps there is middle ground between doing nothing for someone and doing that person's work for them?
> so if you still want to mock me, give me the
> assignment topic then. but dont make it too difficult
> to me, because i am still a college student. (umm, i
> will go to a uni. this Sep.)
Read between the lines, this was about you giving someone a fish rather than teaching them how to fish.
> Read between the lines, this was about you giving someone a fish
> rather than teaching them how to fish.
firstly, please see the comments between my code. i am actually teaching him how to fish. to the person who needs the code, the only difference is whether the code is from a tutorial book or from the forum here.
secondly, it is my business to 'give someone a fish'.
I am assuming you have the String loaded already, or you know how to take input it.
String temp = "I wish I could code.";
int words = 0;
StringTokenizer st = new StringTokenizer(temp);
while (st.hasMoreTokens())
words++;
System.out.println("This is how many words I have: " + words);
go fishin'
> OK, but that's not the question here. And
> what's with all the extra variables ans bad
> naming conventions? Also your code seems to skip first line entirely.
1. bad naming conventions? to you or to all? at least not to me and my lecturer.
2. i just took the second line as an example.
Here's your code fixed. I wouldn't do it this way but...
/*** i wrote it for fun! ***/
String txt = "the text"+'\n'+"has three lines and four four-char words."+'\n'+"can you find them all?";
// lets read the second line of the text;
// count how many four-letter words were read;
int counter = 0;
int currentWordLength = 0;
for (int i = 0; i < txt.length(); i++)
{
char c = txt.charAt(i); // get a buffer character;
// check if it's a letter or number, we ignore hyphenated words and words with underscores etc.
if (Character.isLetterOrDigit(c) || c == '_' || c == '-')
{
currentWordLength++;
}
else
{
if (currentWordLength == 4) counter++;
currentWordLength = 0;
}
}
if (currentWordLength == 4) counter++;
System.out.println(counter);
> now, show me why at the end the counter will be == 1!!
Have you run it? I did.
if (c == '\n')
{
int charkount = k - p;
if (charkount == 5) counter++;
break; // you break after you reach a newline
}
> 1. bad naming conventions? to you or to all? at least
> not to me and my lecturer.
Then you have a bad lecturer. One letter variables such as i in current practice should only be used as a loop counter.
[url=http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html#367]Java Naming Conventions[/url]
"Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters."
> firstly, please see the comments between my code. i
> am actually teaching him how to fish. to the
> person who needs the code, the only difference is
> whether the code is from a tutorial book or from the
> forum here.
First, I'd like to say I like your riduclous use of the [b] tags. Second, do you think he studied your inane answer, deciphered the poorly named variables, etc or do you think he just took the code and ran? Probably the later (hence you gave him a fish).
> secondly, it is my business to 'give someone a
> fish'.
And it is my business to flame idiots.
/*** i rewrote and optimized it for fun! ***/
String sText = "the text"+'\n'+"has three lines and four four-char words."+'\n'+"can you find them all?";
StringTokenizer tokenizer = new StringTokenizer(sText);
int iTotalFours = 0;
while (tokenizer.hasMoreTokens())
{
String sWord = tokenizer.nextToken();
iTotalFours += (sWord.size() == 4 ? 1 : 0);
}
System.out.println("Total 4 letter words: "+String.valueOf(iTotalFours));
> /*** i rewrote and optimized it for fun! ***/String sText = "the text"+'\n'+"has three lines and four four-char words."+'\n'+"can you find them all?";
> StringTokenizer tokenizer = new StringTokenizer(sText);
> int iTotalFours = 0;while (tokenizer.hasMoreTokens()){String sWord = tokenizer.nextToken();
> iTotalFours += (sWord.size() == 4 ? 1 : 0);}
> System.out.println("Total 4 letter words: "+String.valueOf(iTotalFours));
thanks rkconner, i like your code. :-)
> > now, show me why at the end the counter will be == 1!!
> Have you run it? I did.
> if (c == '\n')
> {
>int charkount = k - p;
>if (charkount == 5) counter++;
>break; // you break after you reach a newline
> }
// you break after you reach a newline
yeah, i did so cos the question is to read one line of text.
> One-character variable names should be avoided
> except for temporary "throwaway" variables.
dubwai:
well, according to this statement, my code was not too bad.
some pointers that i would discard after use were given one-character names. but the one i needed to print out (e.g. counter) was given a meaningful name.
so, personally, i dont think the naming conventions of my code were that terrible.
Re: "Then you have a bad lecturer."
Hmmm, definitely yes - ask him (or her?) to use the International standards of the Hungarian Notation (or the link provided above)
" ...so, personally, i dont think the naming conventions of my code were that terrible."
Really? Personally, I think it was awful: in respect to;
A. Naming
B. Style
C. Method
D. Integrity
E. Readbility
F. Efficiency
G. It was a fish
> yeah, i did so cos the question is to read one line of
> text.
To be honest, I wasn't sure that was the problem but I know it didn't look right. Your code was too hard to read and I basically tossed it, which is what I would probably do if you were on my team. You want to know what is wrong with your code? Well here we go...
/*** i wrote it for fun! ***/
String txt = "the text"+'\n'+"has three line and four four_char words."
+'\n'+"can you find them all?";
// p should be named 'pointer' or 'wordStart'
// why do you set a pointer here?
int p = 0;
// why do you use pointer to search?
// just use the one arg search or 0
int i = txt.indexOf('\n',p);
// "increment the pointer;" <- thi comment is
// incorrect, you are not incrementing anything
// again why are you using p for this?
p = i + 1;
// what do you need j for? You already break
// when you hit a newline below
int j = txt.indexOf('\n',p);
// count how many four-letter words were read;
int counter = 0;
p = i; // you finally set the pointer to it's true
// starting position all the other use of it is
// just confusing
// then you don't use it to initialize the counter
// and because you've already used i and j for
// non-throwaway variables you use k as the counter
// k usually isn't used unless it's a nested loop
for (int k = i+1; k<j+1; k++)
{
char c = txt.charAt(k); // get a buffer character;
if (c == '\n') // if End_of_Line;
{
// what do you need charkount for?
// you only reference it once. That's
// wasteful and confusing
int charkount = k - p;
// if (charkcount == 5) doesn't look like
// you are finding a 4 letter word
if (charkount == 5) counter++;
// try avoid break statements in loops
break; // exit the loop;
}
else
{
// why are you creating a new variable to
// just reference it a single time in the
// very next line?
// Just use "if (isWhitespace(c))"
boolean b = Character.isWhitespace(c);
if (b) // if this is a white space;
{
// another distinct charkount variable
// it is confusing to have two variables
// with the same name in a loop like this
// and you don't need it anyway use
// "if ((k - p) == 5)"
int charkount = k-p;
if (charkount == 5)
{
counter++;
// don't call continue unless you have to
// in this case it does nothing that
// wouldn't happen anyway
continue;
}
// the comment below is incorrect
// this is not the else for isWhiteSpace
else // if this is not a white space;
{
// if you set this on the first letter
// of the new word and not the last whitespace
// character before the new word, the comment would
// make a lot more sense
p = k; // reset the pointer so that it
// indicates where the new word will start;
}
}
}
}
>
> Variable names should not start with underscore _ or
> dollar sign $ characters, even though both are
> allowed.
This is one thing that I occasionally get into debates on, as I believe in differentiating between field names and variable names. The former get a leading underscore, the latter don't. I find that it makes for an easier visual scan.
> of its use. One-character variable names should be
> avoided except for temporary "throwaway" variables.
I believe in being more strict here: no one-character variable names whatsoever; a "throwaway" loop index would be something like "ii". The reason is that single-character variables make it impossible to use an editor's search operation.
> I hate hungarian notation and it's almost useless in
> Java.
I also dislike this notation, as it adds work if you decide to change a variable's type (also, do you prefix 99% of your variables/members with "o"?).
However, I do use a similar standard with Swing programming, where variables relating to the same UI element have similar names. For example, "lPassword" for the label associated with a password field, "fPassword" for the field itself.
This is also an issue with "throwaway" variables. Since most GUI elements go out of scope almost instantly, it would seem reasonable to make variables "label0" (not "l0"!) &c. However, again I turn to making a visual scan easier; you clearly see what happens with each UI element (especially important since much of this code is copy-n-paste).
> I believe in being more strict here: no one-character
> variable names whatsoever; a "throwaway" loop index
> would be something like "ii". The reason is that
> single-character variables make it impossible to use
> an editor's search operation.
I've heard this argument before and I agree except that I have never needed to search for true throwaway variables. For example:
int sum;
for (Iterator i = list.iterator(); i.hasNext();) {
sum += ((Integer) i.next()).intValue();
}
Sure we can't search for i effectively, but it's only in scope for two lines of code. I've never looked back and needed to search for i. Throwaway variables, by definition (my definition I suppose) are variables that are used in such short scopes that you never need to search for them. If you need to search for them then they aren't really throwaway.
> Nonsense,
>
> modern coding standards (including your link) have
> 'evolved' from H.N.
Maybe so, maybe not but just because something evolved from something else doesn't make them the same. My understanding of hungarian notation is that you always prefix varaibles with letters and abbreviations letting you know the scope and type of the variable.
The coding standards I use require that you never do that.
So I'm really not sure of your point here.
> This is one thing that I occasionally get into debates
> on, as I believe in differentiating between field
> names and variable names. The former get a leading
> underscore, the latter don't. I find that it makes for
> an easier visual scan.
I think this is a matter of personaly preference as there are pros and cons to both methodologies. Presonally I don't care for underscores, and actually their use has made modifying generated code with regex more complicated.
> I think this is a matter of personaly preference as
> there are pros and cons to both methodologies.
LOL ... this comment got me to thinking about all the different coding standards I've seen (and, as a contractor, had to adapt to), and I've come to the conclusion that it's all a matter of personal preference. Just that my preference is right and everyone else's is wrong.
> LOL ... this comment got me to thinking about all the
> different coding standards I've seen (and, as a
> contractor, had to adapt to), and I've come to the
> conclusion that it's all a matter of personal
> preference. Just that my preference is right and
> everyone else's is wrong.
I don't think that you can say it's all preference. That line of reasoning ends up with the result that no methodology is superior to any other. I think that we can agree that that is not the case.
For example, lets say out project says all variables must be named as a sequence of one lowercase 'l' and nine '1's and 'l's. So in a method we might have:
int l1l1l1l1l1 = 3;
int l1l1l1l1ll = 100;
for (int l111l1l1ll = l1l1l1l1l1; l1l1l1l1l1 < l1l1l1l1ll; l111l1l1ll++) {
l111l1l1ll = l1l1l1l1l1 * l111l1l1ll;
}
No would you argue that this standard is as good as any other coding standard (assuming the purpose of a coding standard is to make code more readable and not less readable.)
"So I'm really not sure of your point here."
Granted, HN has been improved and I prefer the standards that Sun has published but for the optional
if{
//yada-yada-yada
{else{
Hate it! However;-
try{
//yada-yada-yada
{catch(Exception onlyCosIHaveTo){}
I do use (which is an inconsistency on my part)
The point is that the person's lecturer who started this debate doesn't seem to be aware that standards exist.
PS : I also cannot stand _ and $
PPS: hmm, anissue that will never be resolved
> Now you're just being silly.
No, people tend to use, "it's just preference" as an argument to make any point they feel like making i.e. rationalization. Not that anyone is doing that in this thread.
This is not confined to programming. I'm always telling my fiance not to ride her bike on the left side of the road. She feels like it's just her preference but it's not. It's illegal and dangerous to her and others. Last night some genius was riding his bike full clip around a blind curve on the sidewalk. Is that just his preference? The jogger he almost collided with probably doesn't think so.
I might say to someone, "don't point firearms at people unless you intend on shooting them" and that person might argue that it is just his preference to wave guns at people. Does that make it OK? Do you say "alright, I guess it's just your preference." If your cab driver is driving with his knees while smoking crack at 80 miles an hour do you think "it's just his preference."
The point is while there is no absolute right or wrong there are definitely ways to propose criteria and judge whether one thing meets those criteria better than something else. Everyone might not agree, but we can make these arguments and not be defeated by "it's just preference."
> No, people tend to use, "it's just preference" as an
> argument to make any point they feel like making
I continued thinking about coding standards on the drive in today. And, leaving aside the general societal implications of "it's just a preference" (there's a section of Zen and the Art of Motorcycle Maintenance that deals with that), I believe that all coding standards are equal, even the absurdist example you gave.
My reasoning basicly comes down to "any standard is better than no standard." At the heart of that is the idea that people who adopt standards of any sort tend to do so from a desire to prevent sloppy code, and that sloppy code indicates sloppy thinking. Therefore, if you take steps to eradicate sloppy code, you automatically improve your thought process.
As for your example, well, it seems a good way to force people to use accessor methods, n'est pas?
> My reasoning basicly comes down to "any standard is
> better than no standard." At the heart of that is the
> idea that people who adopt standards of any sort tend
> to do so from a desire to prevent sloppy code, and
> that sloppy code indicates sloppy thinking. Therefore,
> if you take steps to eradicate sloppy code, you
> automatically improve your thought process.
I agree that any standard is better than no standard in general, however I don't believe that that equates to all standards being equal. Let me give an analogy (if you haven't noticed, I'm big on analogies.)
Let's say you are a soldier in World War 2. I'm pretty sure you'd agree that having a gun of some sort is better than having no gun at all. However, would you rather have a pistol or a rifle? A rifle or a sub machine gun? A Japanese made submachine gun that isn't reliable or a Thompson gun that is very reliable?
I just can't see how ou can say that all standards are equal. As far as helping with sloppy thinking, I think I can agree, that they are probably all about the same.
But I think a coding standard does more than just prevent sloppiness. I think that it improves readability. If a good standard is adhered to it makes "code scanning," as you say much easier. Hungarian notation, for example makes code harder for me to read, even though I've had to read and write it for years. Often we end up with several varaibles that all start with the same prefix. That confuses my eyes and I can't skim across the code, I have to read it carefully. In that aspect, readability, I find hungarian notation inferior, though, it has it's place in other languages and I can see using it in GUI code (though I prefer not to use it there either.)
I don't pretend to know the absolute truth either. Other people may have perfectly good reasons to disagree.
> I agree that any standard is better than no standard
> in general, however I don't believe that that equates
> to all standards being equal.
I think your analogy might prove my point :-) Let's assume for this argument that the standards are being set down by competent, experienced programmers. I think that recognizing the need for standards is indicative of that, although I recognize that some standards come from clueless managers who've read the latest "how to keep your project from being canceled" book.
If that is the case, then I think that the standards will naturally self-refine to make the programming process easier. Standards that don't help the process will be rejected, but since the people setting the standards don't want to exist without something, they will find replacements that work better.
So, if we can accept that standards self-refine -- that the Thompson submachine gun, which jammed frequently, will be replaced by the M16 -- I think we can conclude that different standards are indeed equal.
Personally, I don't like K&R indentation style, and never have. But for people who have used it extensively, I'm sure that it is just as valid as my "braces on separate lines" style. You don't like the underscore prefix on member variables, I do; again, I think this comes down to familiarity (and maybe a philosophical decision of whether there's any real difference between member vars and local vars).
As for Hungarian Notation, I think it will eventually disappear with strongly-typed languages, as it is difficult to scan and offers no benefits. However, I think it will remain with weakly-typed languages, as it gives programmers an extra level of understanding of the code.
> If that is the case, then I think that the standards
> will naturally self-refine to make the programming
> process easier. Standards that don't help the process
> will be rejected, but since the people setting the
> standards don't want to exist without
> something, they will find replacements that
> work better.
I can agree with that.
> So, if we can accept that standards self-refine --
> that the Thompson submachine gun, which jammed
> frequently, will be replaced by the M16 -- I think we
> can conclude that different standards are indeed
> equal.
No, I'm pretty sure that the Thompson gun was one of the most reliable submachine guns of the time. It was vastly superior to the Japanese submachine guns.
"One of the main assets of the Thompson submachine gun was reliability; it performed better than most submachine guns when exposed to dirt, mud and rain."
http://www.rt66.com/~korteng/SmallArms/thompson.htm
It even was used during the Korean war. The main reason it was replaced was that it was inaccurate, lacked high penetration and most of all, it was extremely expensive to make. I think it cost $300 or $500 to make during WWII and that was a lot of money back then. I was largely replaced by the "grease gun" which was easier to make and it's lower tolerances made it even more reliable.
In contrast, when the M16 was first produced, the bureaucrats decided to remove the chrome plating from the action to save money. This resulted in the extremely poor reliability of the M16 when intially introduced in Vietnam. In fact many American soldiers would carry a AK47 (a weapon almost 2 decades old) if they could get their hands on them.