Stylistic note on loops

M

markspace

I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

A lot of the processing I'm currently doing involves finding a
particular character, and then doing something with the text up to that
point. For example:

int i;
for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
{}
// do something with i and s here

This marches ahead until it find a character that isn't a "letter",
then, with i set to the offset of the last letter+1, is able to do
something with that group of letters in string s.

My question is on the code style I used here. The for loop looks a
little funny. I think it's the best because all the terms (is that
right? terms = the bits between the semicolons) of the for statement do
the right thing and are in the standard position.

However, the body is empty, which is weird, and i has to be declared
outside of the for loop so I can use it later, which is a little weird.

Any thoughts on how to format this? Would a while loop be better or
more readable here?

int i = 1;
while( Character.isLetter( s.charAt( i ) ) ) {
i++;
}

That while loop wasn't tested, but should do the same thing as the for
loop above. Any ideas?
 
L

Lew

I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

A lot of the processing I'm currently doing involves finding a
particular character, and then doing something with the text up to that
point.  For example:

     int i;
     for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
     {}
     // do something with i and s here

This marches ahead until it find a character that isn't a "letter",
then, with i set to the offset of the last letter+1, is able to do
something with that group of letters in string s.

My question is on the code style I used here.  The for loop looks a
little funny.  I think it's the best because all the terms (is that
right? terms = the bits between the semicolons) of the for statement do
the right thing and are in the standard position.

However, the body is empty, which is weird, and i has to be declared
outside of the for loop so I can use it later, which is a little weird.

Any thoughts on how to format this?  Would a while loop be better or
more readable here?

   int i = 1;
   while( Character.isLetter( s.charAt( i ) ) ) {
      i++;
   }

That while loop wasn't tested, but should do the same thing as the for
loop above.  Any ideas?

Use what you like, that's why it's called "style". I strongly
recommend against single-letter variable names like "i" and "s",
though.

Personally I prefer the 'for' version. There's nothing "weird" about
the index being declared outside the loop body since that's driven by
the actual scope needed. The only thing "weird" is to declare a
variable for a different scope than it needs, but you're not doing
that.

There is equally nothing "weird" about an empty loop body. It's done
all the time. In fact, that's part of why the 'for' syntax is what it
is, going back to 'C' days and beyond - to support compact expression
of a loop.

Go with your 'for' loop, it's bog standard.
 
B

bcr666

I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

A lot of the processing I'm currently doing involves finding a
particular character, and then doing something with the text up to that
point.  For example:

     int i;
     for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
     {}
     // do something with i and s here

This marches ahead until it find a character that isn't a "letter",
then, with i set to the offset of the last letter+1, is able to do
something with that group of letters in string s.

My question is on the code style I used here.  The for loop looks a
little funny.  I think it's the best because all the terms (is that
right? terms = the bits between the semicolons) of the for statement do
the right thing and are in the standard position.

However, the body is empty, which is weird, and i has to be declared
outside of the for loop so I can use it later, which is a little weird.

Any thoughts on how to format this?  Would a while loop be better or
more readable here?

   int i = 1;
   while( Character.isLetter( s.charAt( i ) ) ) {
      i++;
   }

That while loop wasn't tested, but should do the same thing as the for
loop above.  Any ideas?

I frequently use a for loop to empty a table something like:
for (;table.getRowCount() > 0;table.removeRow(0));
notice, you don't even need the body {}, if your body is empty or one
line, you can use just a ; to end.

You mention though that you are looking for a particular character,
maybe you should use "some-string-is-here".split("-"). This will give
you an String[] of strings without the -. Another option is "some-
string-is-here".firstIndexOf("-") will tell you the position of the
first "-".
 
F

Fred

Use what you like, that's why it's called "style".  I strongly
recommend against single-letter variable names like "i" and "s",
though.

Personally I prefer the 'for' version.  There's nothing "weird" about
the index being declared outside the loop body since that's driven by
the actual scope needed.  The only thing "weird" is to declare a
variable for a different scope than it needs, but you're not doing
that.

There is equally nothing "weird" about an empty loop body.  It's done
all the time.  In fact, that's part of why the 'for' syntax is what it
is, going back to 'C' days and beyond - to support compact expression
of a loop.

Go with your 'for' loop, it's bog standard.

It is suspicious that you start the loop at the second character
(i=1). This will likely cause problems when s is empty or the first
character is not a letter.
 
T

Tom McGlynn

I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

A lot of the processing I'm currently doing involves finding a
particular character, and then doing something with the text up to that
point.  For example:

     int i;
     for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
     {}
     // do something with i and s here

This marches ahead until it find a character that isn't a "letter",
then, with i set to the offset of the last letter+1, is able to do
something with that group of letters in string s.

...
Any thoughts on how to format this?  Would a while loop be better or
more readable here?

While I don't have any problem with the style for the problem as
stated, I think it tends to degrade when there are more conditions,
and I often find there are. E.g., if you aren't guaranteed that there
is any non-alphabetic character then you need:

for (i=1; i<s.length() && Character.isLetter(s.charAt(i)); i += 1)
{
}

This I would prefer to see as:

for (i=1; i<s.length(); i += 1) {
if (Character.isLetter(s.charAt(i)) {
break;
}
}

The extra test is also needed if, as another poster noted, the string
may only be one character long.

This separates the loop structure from the logic test which I find
easier to follow.

Regards,
Tom McGlynn
 
B

BGB / cr88192

markspace said:
I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

A lot of the processing I'm currently doing involves finding a particular
character, and then doing something with the text up to that point. For
example:

int i;
for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
{}
// do something with i and s here

This marches ahead until it find a character that isn't a "letter", then,
with i set to the offset of the last letter+1, is able to do something
with that group of letters in string s.

My question is on the code style I used here. The for loop looks a little
funny. I think it's the best because all the terms (is that right? terms
= the bits between the semicolons) of the for statement do the right thing
and are in the standard position.

we call these 'expressions'.
not to be confused with 'statements', which are what the variable
declaration and for loop are.

However, the body is empty, which is weird, and i has to be declared
outside of the for loop so I can use it later, which is a little weird.

actually, the braces can be omitted here, hence:
for( i = 1; Character.isLetter( s.charAt( i) ); i++ );

braces generally only really serve the purpose of lumping multiple
statements together into a single statement block, and so are typically left
out when there is only a single statement.

further more, if there is no statement, a single ';' can be used instead,
which is usually understood as being an "empty statement" or "null
statement", ane may be used with 'for' and 'while' loops, or wherever else
they may be useful.


note:
declaring variables outside the loop is also fairly common, and in fact many
people use this as their primary style (it is declaring variables inside the
for loop which is itself unusual...).

anyways, functionality is more important than some perception of style.

Any thoughts on how to format this? Would a while loop be better or more
readable here?

int i = 1;
while( Character.isLetter( s.charAt( i ) ) ) {
i++;
}

That while loop wasn't tested, but should do the same thing as the for
loop above. Any ideas?

again, the braces are optional.

while( Character.isLetter( s.charAt( i ) ) ) i++;
or, taken further:
while(Character.isLetter(s.charAt(i++)));

or, if Java were C or C++...:
while(isalpha(s[i++]));
or:
while(isalpha(*s++));
(the above will not work in Java, but are meant more as illustration).


but, to a large degree, style is irrelevant...
it is much more important that code work than that it adhere to any
particular sense of aesthetics, or at least within the realm of basic sanity
(for example, using indentation and not organizing code into a single big
lump of characters and similar...).

even then, there are cases where it is infact nicer to lump a bunch of
statements onto a single line, and other cases where it is best to insert
extra whitespace, and so no simple rules are always ideal.


someone here also advocated the use of longer / "descriptive" variable
names, but again, this is another one of those points of conflict, and is
ultimately irrelevant and depending primarily what one is doing. the main
cost of longer names is that they take more screen space and more mental
letter-space to store and work with, which is a drawback, and also longer
names can become particularly awkward.

so, single letter names are convinient and usually "obvious enough", which
leaves longer names (words, multi-words, ...) mostly for cases where the
usage of a variable is not immediately obvious or driven by convention (most
single-letter variable names are somewhat driven by informal conventions, so
it is understood what the names are regardless of their brevity).

in some cases, one may also have reason for using "hungarian notation",
although people get into arguments over this as well.

but, ultimately, it is all pointless.
do what makes sense in a given situation, and this is good enough...
 
M

markspace

You mention though that you are looking for a particular character,
maybe you should use "some-string-is-here".split("-"). This will give
you an String[] of strings without the -. Another option is "some-
string-is-here".firstIndexOf("-") will tell you the position of the
first "-".


This is good advice. split() isn't exactly a good match here but
firstIndexOf() will be useful, thanks for reminding me.

Here's another one, designed to skip over a set of characters. I
thought I could implement the inner loop with skip.contains( s.charAt(
cursor) ) but contains only takes CharSequence, not char. Bummer.

public static int skip( String s, int offset, String skip ) {
int cursor = offset;
testing_string:
for( ; cursor < s.length(); cursor++ ) {
for( int i = 0; i < skip.length(); i++ ) {
if( s.charAt( cursor ) == skip.charAt( i ) ) {
continue testing_string;
}
}
break testing_string;
}
return cursor;
}
 
L

Lew

BGB said:
actually, the braces can be omitted here, hence:
     for( i = 1; Character.isLetter( s.charAt( i) ); i++ );

braces generally only really serve the purpose of lumping multiple
statements together into a single statement block, and so are typically left
out when there is only a single statement.

"... are typically left out ..." - you make that sound like such a
universal rule when in fact most places mandate the opposite, and most
writers recommend the opposite, that the braces are needed even for a
single body statement to prevent anomalies due to obfuscatory
indentation during a refactoring or enhancement activity.

I suggest that the best practice of using curly braces even for single-
statement bodies is what is "typical". If not, it should be.
further more, if there is no statement, a single ';' can be used instead,
which is usually understood as being an "empty statement" or "null
statement", ane may be used with 'for' and 'while' loops, or wherever else
they may be useful.

note:
declaring variables outside the loop is also fairly common, and in fact many
people use this as their primary style (it is declaring variables inside the
for loop which is itself unusual...).

Huh? Wha...?

This isn't a popularity contest. You declare a variable for the scope
for which it applies. If a variable has no use outside the loop body,
it should be declared inside the loop body. What patzer programmers
do notwithstanding.

Where are you getting your statistics, anyway? Declaring variables
inside a loop body is darn-near universal. How in the seven worlds do
you call that "unusual"?
anyways, functionality is more important than some perception of style.

Precisely, so declare variables outside the loop if, and only if,
they're used outside the loop.
again, the braces are optional.

By the rules of the language, not by best practice.
while( Character.isLetter( s.charAt( i ) ) ) i++;

Ewwwww!

or, taken further:
while(Character.isLetter(s.charAt(i++)));

Do you enjoy making your code difficult for others to read?
but, to a large degree, style is irrelevant...

Nope.

To a large degree, style is relevant - it's to the degree that people
need to work comfortably together.
it is much more important that code work than that it adhere to any
particular sense of aesthetics, or at least within the realm of basic sanity
(for example, using indentation and not organizing code into a single big
lump of characters and similar...).

I thought from your code snippets that you were in favor of "a single
big lump of characters and similar...". I'm pleased to be mistaken.
even then, there are cases where it is infact nicer to lump a bunch of
statements onto a single line, and other cases where it is best to insert
extra whitespace, and so no simple rules are always ideal.

But simple principles are ideal - make code easy to read and
understand, and hard to misconstrue or screw up.
someone here also advocated the use of longer / "descriptive" variable
names, but again, this is another one of those points of conflict, and is

It's only a "conflict" between those who care about maintainability
and those who utterly lack professionalism. The former have no issue
with using longer, more readable names. The latter have no clue why
it's important.
ultimately irrelevant and depending primarily what one is doing. the main
cost of longer names is that they take more screen space and more mental
letter-space to store and work with, which is a drawback, and also longer
names can become particularly awkward.

What you're saying is true for names that are "too long", but not
names that are "longer". Descriptive names are not perceived
psychologically as "letter-space", whatever the freak that is supposed
to mean, but as morphemes and memes - i.e., the mind chunks the
information, so your claim about "more mental letter-space" is as
bogus as the terminology.
so, single letter [sic] names are convinient and usually "obvious enough", which

Sez you! You aren't really correct, but it's a nice opinion.

Single-letter names are only "convenient" for the lazy author.
They're a lot of work for the diligent maintainer. I In a word,
they're selfish.
leaves longer names (words, multi-words, ...) mostly for cases where the
usage of a variable is not immediately obvious or driven by convention (most

or for where you want clarity, lack of error, maintainability,
professionalism, ...
single-letter variable names are somewhat driven by informal conventions, so
it is understood what the names are regardless of their brevity).

"It is understood" - you are fond of using the passive voice to make
your minority opinions sound like Universal Truth.
in some cases, one may also have reason for using "hungarian notation",
although people get into arguments over this as well.

Probably because there's no use for it in Java, and it violates the
well-founded and well-understood principles of encapsulation and
information-hiding.
but, ultimately, it is all pointless.

Now we're talking about life in general.
do what makes sense in a given situation, and this is good enough

Spoken like an amateur.
 
A

Arne Vajhøj

I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

A lot of the processing I'm currently doing involves finding a
particular character, and then doing something with the text up to that
point. For example:

int i;
for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
{}
// do something with i and s here

This marches ahead until it find a character that isn't a "letter",
then, with i set to the offset of the last letter+1, is able to do
something with that group of letters in string s.

My question is on the code style I used here. The for loop looks a
little funny. I think it's the best because all the terms (is that
right? terms = the bits between the semicolons) of the for statement do
the right thing and are in the standard position.

However, the body is empty, which is weird, and i has to be declared
outside of the for loop so I can use it later, which is a little weird.

Any thoughts on how to format this? Would a while loop be better or more
readable here?

int i = 1;
while( Character.isLetter( s.charAt( i ) ) ) {
i++;
}

That while loop wasn't tested, but should do the same thing as the for
loop above. Any ideas?

I would go for the while loop in this case.

It is logically a while operation and not a for operation.

Arne
 
B

BGB / cr88192

BGB / cr88192 wrote:

<snip>

nevermind that we disagree on many matters of style...

I still regard that style is largely unimportant in most cases, since the
language does not require it, and it is not like much actually bad will
happen due to violating some stylistic rule, anymore than fire will fall
from the ceiling due to using the wrong silverware or stiring ones' coffee
with a knife or screwdriver or similar...


any rules one follows are usually due to some specific or potential cost of
violating it, and if a rule does not result in some obvious cost, why
bother?

like the braces:
one can leave them out, and save some characters, and if later they need
multiple statements, they can put them back in. usually the savings (in
terms of readability and screen space) save more than the effort needed to
type them back in later if the code is being edited.

in all likelyhood, if one initially is only typing a single statement,
likely they will never need multiple statements anyways, and hence the
screen-space savings will be of a larger benefit.

in some cases, one may also have reason for using "hungarian notation",
although people get into arguments over this as well.

<--
Probably because there's no use for it in Java, and it violates the
well-founded and well-understood principles of encapsulation and
information-hiding.
-->

it is useful in those cases where otherwise it would be difficult to come up
with good non-clashing variable names, or in cases where several variables
are closely related but represent different entities. hungarian notation
allows the basic-name to be used multiple times.

granted, it is pointless for methods given the existence of overloading...

but, ultimately, it is all pointless.

<--
Now we're talking about life in general.
-->

well, more specifically, about language style and debating over language
style.
what really does it matter?

do what makes sense in a given situation, and this is good enough

<--
Spoken like an amateur.
-->

I have written and worked on projects in the Mloc range (including 3D
engines and compilers and similar), and in a number of different programming
languages (C, C++, ASM, Java, C#, ...), so I will contest this description.
 
S

Stefan Ram

markspace said:
int i;
for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
{}
// do something with i and s here
However, the body is empty, which is weird, and i has to be declared
outside of the for loop so I can use it later, which is a little weird.

The weird things are (others might have noticed this already,
I have not read the thread yet):

- i starts at 1.

- »( i)« has a space in front of the »i«, but not after it.

(I'd write »( s.charAt( i ))«, but this is only my very
personal style, see
http://www.purl.org/stefan_ram/pub/c_format_en .)

I'd write this as:

int i = -1; while( Character.isLetter( s.charAt( ++i ));
 
S

Stefan Ram

Patricia Shanahan said:
I disagree, strongly, with the idea of using ";" instead of braces
containing a comment. A ";" after the ")" of a for-statement could be a
typo.

In fact, nearly everything could be a typo in source code.
Someone else reading the code is going to stop and think
about whether the following statement should be the for-loop
body, especially if it uses "i".

Usually, I assume that the programmer intented what he wrote,
unless I have a reason to assume otherwise. Such a semicolon »;«
is not such a reason. An »{ /* EMPTY */ }« makes me feel
somewhat annoyed/offended.

NB: THE PERIOD AT THE END OF THE PREVIOUS SENTENCE WAS
WRITTEN INTENTIONALLY TO MARK THE END OF THE SENTENCE.
SEE: http://en.wikipedia.org/wiki/Full_stop
 
L

Lew

I have written and worked on projects in the Mloc range (including 3D
engines and compilers and similar), and in a number of different programming
languages (C, C++, ASM, Java, C#, ...), so I will contest this description.

How about we construe "amateur" in the good sense of "one who loves the art"?

Also, the word was "like", not "as". I do not actually think that you are an
amateur, construed in the derogatory sense.

On rereading your post your arguments do make more sense than they seemed a
couple of hours ago. Mind you, I don't fully agree, but from a perspective
they do hang together.
 
L

Lew

markspace said:
I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

Now *this* is good use o' Usenet!

Besides that, it's the highest form of programming - seeking review and comment.

Good show, old chap!
 
S

Stefan Ram

»{ /* EMPTY */ }«

It reminds me of suggestions to write

Character.isLetter( s.charAt( i ))== true

, because this is »more readable« than

Character.isLetter( s.charAt( i ))

. It might be more readable for persons who know English,
but no or little Java. But source code becomes less readable
for experienced programmers when it is written with such a
reader in mind.

In C, to skip two space-separated integral numerals
(under certain circumstances):

while( isnum( *++c )); while( isspace( *++c )); while( isnum( *++c ));

, this is obvious and intelligible. Now try to scan this:

while( isnum( *++c ))
{ /* EMPTY */ }

while( isspace( *++c ))
{ /* EMPTY */ }

while( isnum( *++c ))
{ /* EMPTY */ }

The »{ /* EMPTY */ }« only distracts the attention of the reader
towards unimportant parts of the code, gives way to more errors,
like forgetting to close the comment properly and bloats the code.
 
L

Lew

It reminds me of suggestions to write

Character.isLetter( s.charAt( i ))== true

, because this is »more readable« than

Character.isLetter( s.charAt( i ))

. It might be more readable for persons who know English,
but no or little Java. But source code becomes less readable
for experienced programmers when it is written with such a
reader in mind.

In C, to skip two space-separated integral numerals
(under certain circumstances):

while( isnum( *++c )); while( isspace( *++c )); while( isnum( *++c ));

, this is obvious and intelligible. Now try to scan this:

while( isnum( *++c ))
{ /* EMPTY */ }

while( isspace( *++c ))
{ /* EMPTY */ }

while( isnum( *++c ))
{ /* EMPTY */ }

The »{ /* EMPTY */ }« only distracts the attention of the reader
towards unimportant parts of the code, gives way to more errors,
like forgetting to close the comment properly and bloats the code.

On the third hand, one might reasonably find

while( isnum( *++c )){} while( isspace( *++c )){} while( isnum( *++c )){}

equally or even more obvious and intelligible whilst emphasizing a) the
loopness of each loop and b) the deliberateness of the act - four strokes
(counting SHIFT) bespeaks commitment a lone semicolon tap might not - without
undue sacrifice of terseness. The very shock-value of the idiom helps
document itself.
 
B

BGB / cr88192

Lew said:
How about we construe "amateur" in the good sense of "one who loves the
art"?

ok, fair enough.


admittedly, Java is not one of my most heavily used languages (much more of
my development is in C and C++, and of this, a much larger portion is in C).

it is possible that some amount of C-like stylistic preferences bleed over.


admittedly, there is a notion I have heard before, that when a person moves
from one language to another, their style should also entirely change as
well to be whatever is most accepted by the particular
language/community/... personally, I find this idea both inconvinient and
unecessary, given that these languages retain mostly similar syntax (and
what works aesthetically in one language should work similarly well in the
others, and if there is a severe conflict then this would imply that maybe
something is not right).

although, this is not to say that one should dogmatically stick to an older
style either, since if one is working on a piece of code and introduces a
harsh style change from whatever is already there, then this will be ugly
regardless of the relative merits of the stylistic conventions in use (or
worse yet is trying to impose a new style on already existing code).

for example, going and changing a bunch of Java code to use
'FirstLetterCaps' naming, or a bunch of C# code to use 'camelCase' because
one has a particular preference would be IMO ill-advised, even though there
is little requirement either way that Java be camelCase or C# be
FirstLetterCaps, so one can probably choose which to use based on both
convention and personal preferences (weighting things as they go).

actually, I have seen cases where people have gone around and changed all
the capitalization or indentation or whatever else in an existing codebase,
and IMO this is ugly and inconvinient, as then often pieces of older code
will no longer work simply because the capitalization is different (and then
one has to stub things or modify the code or similar to make it fit again).


similar goes for little style wars and artificial divisions between C and
C++, when as I see it, since it is more or less a simple subset/superset
issue, why not treat it as such?...

at least with C (or C++) vs Java, there are good reasons why things done one
way in one language are not done in the same way in the other, ...

admittedly, I have my own little rules and practices, but most are more
generally related to practical concerns than some abstract notion of
"language purity" or "style purity" or similar.

Also, the word was "like", not "as". I do not actually think that you are
an amateur, construed in the derogatory sense.

On rereading your post your arguments do make more sense than they seemed
a couple of hours ago. Mind you, I don't fully agree, but from a
perspective they do hang together.

yes, ok.
 
A

Arne Vajhøj

"... are typically left out ..." - you make that sound like such a
universal rule when in fact most places mandate the opposite, and most
writers recommend the opposite, that the braces are needed even for a
single body statement to prevent anomalies due to obfuscatory
indentation during a refactoring or enhancement activity.

I suggest that the best practice of using curly braces even for single-
statement bodies is what is "typical". If not, it should be.

It is the recommendation in the standard SUN/Oracle Java coding
convention.

http://www.oracle.com/technetwork/java/codeconventions-142311.html#15395

<quote>
Braces are used around all statements, even single statements, when they
are part of a control structure, such as a if-else or for statement.
This makes it easier to add statements without accidentally introducing
bugs due to forgetting to add braces.
Huh? Wha...?

This isn't a popularity contest. You declare a variable for the scope
for which it applies. If a variable has no use outside the loop body,
it should be declared inside the loop body. What patzer programmers
do notwithstanding.

Where are you getting your statistics, anyway? Declaring variables
inside a loop body is darn-near universal. How in the seven worlds do
you call that "unusual"?

The "universal" does not apply to C89 and a few other widely used
languages.
Single-letter names are only "convenient" for the lazy author.
They're a lot of work for the diligent maintainer. I In a word,
they're selfish.

i,j and k are idiomatic for for loops.

Arne
 
E

Eric Sosman

I'm doing some text parsing and I'd appreciate some input on code styles
for loops.

A lot of the processing I'm currently doing involves finding a
particular character, and then doing something with the text up to that
point. For example:

int i;
for( i = 1; Character.isLetter( s.charAt( i) ); i++ )
{}
// do something with i and s here

This marches ahead until it find a character that isn't a "letter",
then, with i set to the offset of the last letter+1, is able to do
something with that group of letters in string s.

You'd better hope that such a non-letter character exists, or
you'll march right off the end of the string ...
My question is on the code style I used here. The for loop looks a
little funny. I think it's the best because all the terms (is that
right? terms = the bits between the semicolons) of the for statement do
the right thing and are in the standard position.

However, the body is empty, which is weird, and i has to be declared
outside of the for loop so I can use it later, which is a little weird.

Any thoughts on how to format this? Would a while loop be better or more
readable here?

int i = 1;
while( Character.isLetter( s.charAt( i ) ) ) {
i++;
}

That while loop wasn't tested, but should do the same thing as the for
loop above. Any ideas?

Either is all right (once you fix the end-of-string issue).
The wide scope of `i' is usually not an issue, because it's quite
likely that after you've peeled off the leading letters you'll want
to do something with the rest of the string, and `i' will thus have
a significance that extends beyond the immediate search loop.

If it makes you uncomfortable, though, you can always encapsulate
the search in a method like

static int findFirstNonLetterIgnoringCharAt0(String s) ...
 
A

Arne Vajhøj

actually, the braces can be omitted here, hence:
for( i = 1; Character.isLetter( s.charAt( i) ); i++ );

braces generally only really serve the purpose of lumping multiple
statements together into a single statement block, and so are typically left
out when there is only a single statement.

No. In Java we typical use them even for single statements.
but, to a large degree, style is irrelevant...

No. Reading code that uses different styles or very unusual
styles make reading code slower.

Slower = cost more $$$$ for maintenance.

$$$$ is relevant in professional software development.
in some cases, one may also have reason for using "hungarian notation",
although people get into arguments over this as well.

Even MS has given up on that.
but, ultimately, it is all pointless.
do what makes sense in a given situation, and this is good enough...

Wrong.

It would absolutely terrible if every generation of developers had
to learn everything from scratch instead of benefiting from
best practices learned by previous generations of developers.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top