problem with while statements..

J

justineee

Hi,
I'm trying to build a E-Dictionary program for my project at school.
Don't mind the "E-Dictionary" thing, it's just the program name.

The program should collect words inputted by the user using the
interface I created. Well, I'm quite new in java.. The problem here is
when I enter a word.. All the elements in the array will be that word.
What I want is that with every press of the "addButton", it will wait
for me to input again another word until I fill all the size of the
array.

I know there is something wrong with my while statement but I don't
know how to fix it.

This is just a part of the whole thing.



if (jnd.getSource()==addButton && (!(inputAdd.equals(""))))
{

String getInputAdd = new String();
getInputAdd = inputAdd.getText();

inputAdd.setText("");
int ctr = 0;
while(ctr < arrayWords.length)
{
textArea.append((ctr+1)+". ");
arrayWords[ctr]=getInputAdd;
textArea.append(arrayWords[ctr]+"\n");
ctr++;

if (ctr == (arrayWords.length-1))
{
addButton.setEnabled(false);
setButton.setEnabled(true);
}
}
}


Anyone tips please? :)
 
R

Robert Klemme

Hi,
I'm trying to build a E-Dictionary program for my project at school.
Don't mind the "E-Dictionary" thing, it's just the program name.

The program should collect words inputted by the user using the
interface I created. Well, I'm quite new in java.. The problem here is
when I enter a word.. All the elements in the array will be that word.
What I want is that with every press of the "addButton", it will wait
for me to input again another word until I fill all the size of the
array.

I know there is something wrong with my while statement but I don't
know how to fix it.

This is just a part of the whole thing.



if (jnd.getSource()==addButton && (!(inputAdd.equals(""))))
{

String getInputAdd = new String();
getInputAdd = inputAdd.getText();

Throw that "new String()" out - immediately!! Do not even think about
taking on this habit!
inputAdd.setText("");
int ctr = 0;
while(ctr < arrayWords.length)

Are you aware that you can use a /for/ loop here as well? The advantage
would be that you can add the declaration of /ctr/ to the /for/ loop and
the increment as well.
{
textArea.append((ctr+1)+". ");
arrayWords[ctr]=getInputAdd;

You're assigning every array element the same String so all are
identical. Works as designed. :)
textArea.append(arrayWords[ctr]+"\n");
ctr++;

if (ctr == (arrayWords.length-1))
{
addButton.setEnabled(false);
setButton.setEnabled(true);
}
}
}


Anyone tips please? :)

Cheers

robert
 
R

RedGrittyBrick

justineee said:
Hi,
I'm trying to build a E-Dictionary program for my project at school.
Don't mind the "E-Dictionary" thing, it's just the program name.

The program should collect words inputted by the user using the
interface I created. Well, I'm quite new in java.. The problem here is
when I enter a word.. All the elements in the array will be that word.
What I want is that with every press of the "addButton", it will wait
for me to input again another word until I fill all the size of the
array.

I know there is something wrong with my while statement but I don't
know how to fix it.

I think your problem is not with the syntax of Java's while statement
but with understanding the flow of execution in your program.

This is just a part of the whole thing.

I assume this is part of an ActionListener for the "Add" button.
if (jnd.getSource()==addButton && (!(inputAdd.equals(""))))
{

String getInputAdd = new String();
getInputAdd = inputAdd.getText();

inputAdd.setText("");
int ctr = 0;

This counter 'ctr' variable should be declared in the same place & scope
as the arrayWords array. Note that using a List would be much simpler.

while(ctr < arrayWords.length)

Remove this loop, iteration is by the user clicking the "Add" button.
Your code later disables the "Add" button when the array is full. The
loop is not needed.

{
textArea.append((ctr+1)+". ");

textArea.append(ctr++ + ". " + getInputAdd);
arrayWords[ctr]=getInputAdd;

If you don't use this array anywhere else you can remove it.
textArea.append(arrayWords[ctr]+"\n");
ctr++;

Those two lines are not needed after the above change.
if (ctr == (arrayWords.length-1))

I code defensively:

if (ctr >= (arrayWords.length-1))

This is just in case ctr isn't what I think it is. Out-by-one errors are
common in a lot of coding. Especially in languages with zero-based array
indices.
 
A

Andreas Leitgeb

RedGrittyBrick said:
... Out-by-one errors are common in a lot of coding.
Especially in languages with zero-based array indices.

Especially? how's that?

I'd expect it to be most frequent in whatever index-base
the programmer at hand is least used to.
 
R

RedGrittyBrick

Andreas said:
Especially? how's that?

I'd expect it to be most frequent in whatever index-base
the programmer at hand is least used to.

Yes, exactly. The programmer at hand is always more used to an index
base of 1.

When your mother taught you to count she did not hold up page three of
the book and say, "How many bunnies are there in the picture Andreas?
There are three bunnies! Let's count them: zero, one, two".

When people count the pennies in their pocket they count 1,2,3.

When they are new to programming and index the elements in their array
they sometimes forget to perform the mental shift necessary which says
the first element is, er, the zeroth element and the second element is
element 1. I think it takes a while before people get used to this.

Another reason may be that with a 1-based arrays you would iterate from
1 to n where n is the length. With zero-based arrays you iterate from 0
to n-1. Sometimes new programmers accidentally omit the -1 from the end
condition, because it is slightly unnatural.


Many decades ago in my first job as a trainee programmer I was lent a
copy of The Elements of Programming Style by Kernighan and Plauger.
After reading it I was given a two page summary of "Points from
Kernighan and Plauger". I still have it on my desk. One of the points
under "Common Blunders" is "Watch out for off-by-one errors".


It's actually interesting to look at this list because, although it was
written with Fortran IV in mind, it still contains a lot of advice about
problems I see regularly in this newsgroup.

10.0 times 0.1 is hardly ever 1.0
Don't compare floating point numbers solely for equality
Identify bad input: recover if possible
Write and test big programs in small pieces
Choose data representation that makes the program simple
Choose variable names that won't be confused
Make it right before you make it faster
Make it fail-safe before you make it faster
Make it clear before you make it faster
Let your compiler do the simple optimisations
Don't diddle code to make it faster - choose a better algorithm

and so on
 
R

Roedy Green

int ctr = 0;
while(ctr < arrayWords.length)

Whenever you know to start the count of how many item you will
process, use a for loop.

There are no comments in your program. What others need more than
anything else is comments about your INTENT. What you hoped the code
would do. It is obvious to you, at least for now. when you come back
to you code, you can always figure out the detail, but you CAN'T
easily figure out the overall intent.
 
R

RedGrittyBrick

Peter said:
That depends on how you are interpreting the index.


You're not talking about indices there. You're describing ordinals.

Did you mean cardinals?

The FIRST element of a zero-based array is at INDEX 0. But it's still
the first element, and if I'm counting elements, I'm still going to
start at one. It's ORDINAL is 1.

"The finite ordinals (and the finite cardinals) are the natural numbers:
0, 1, 2" - Wikipedia.

Curious but I'm not sure I care who is right, To me, *ordinals* are
numbers used to define the *order* of a bunch of things.

If I had a dog a cat and a monkey, I could presumably assign them the
respective ordinals 327, 77 and 101. I do feel I could use those
ordinals to order those animals.

In case you take me literally: I am not advocating that Java should be
changed to use those numbers as the first three ordinals (or indices) :)

On the other hand, if I've got three rabbit hutches, and someone asks me
how far from the first rabbit hutch the hutch for rabbit #3 is, the
answer is "two rabbit hutches". That is, the index of the hutch is 2,
not three.

Hang on, you can't use distances a-priori to decide a one true system of
indexing. I'm pretty sure that people had multiple rabbit hutches prior
to the widespread use of the concept of zero. The absence of a formal
zero in their counting system presumably didn't prevent them from
working out which hutch was (say) three hutches from the second.

Let me try substituting 5,9 and 4 for your 1, 3 and 2:

On the other hand, if I've got nine rabbit hutches, and someone
asks me how far from the fifth rabbit hutch the hutch for rabbit #9
is, the answer is "four rabbit hutches". That is, the index of the
hutch is 4, not nine.

No, your logic is unpersuasive to me.

For some people, perhaps. But only if they insist on continuing to use
ordinals as if they were indices.

People make mistakes. That's what I'm talking about. People have habits,
sometimes those habits are suboptimal for a new situation. It takes time
to change them. It isn't a question of anyone *insisting* on doing
something inappropriate.

In any case, once a programmer has
developed the proper habits for a zero-based language, it's every bit as
problematic for them to switch to a one-based language as it might have
been for them to learn the zero-based language in the first place.

I'm happy for us to disagree on this subjective point. At least I don't
have any firm evidence, do you know of any?

And really, doesn't it make more sense for most languages to cater to
the _experienced_ programmer?

You seem to be broadening the discussion into a new area, I wasn't
advocating that Java should be any different than it is.

I mean, sure...sometimes you want a
language that is tailored for beginners. But most of the time, you want
a language that is designed for reasons other than a need to hold a
beginner's hand. Designing a language to fit the often-awkward and
always-inconsistent human experience seems like a sure-fire recipe for a
language poorly suited to instructing computers.

I was under the impression that all designers of high-level programming
languages do indeed try to do the latter to a large extent.

I'm glad I can write my numeric literals in decimal.

The mature programmer, with enough experience in zero-based arrays,
never writes "n - 1" as the end condition. Instead, they iterate from 0
inclusive to n exclusive (i.e. "for (int i = 0; i < n; i++)"). It's
quite natural, especially once you understand the difference between an
ordinal and an index.

You make a good point. I do that myself. The OP didn't. I thought I was
discussing what novices do, not what experienced programmers do.

Not bad advice. But off-by-one errors can be present whether one's
using zero-based or one-based indices.
True.


Frankly, it's been quite awhile
since I've written an off-by-one error myself,

Frankly, when I wrote "new programmer" and "trainee programmer" I wasn't
thinking of you Pete.

but when they do happen,
it's not because of the index base. It's for other less general
reasons. In fact, I'd say the most common off-by-one error I've seen in
code (my own and others) are with respect to calculations like that done
for a binary search, where it's not the beginning or end of the array
that's of interest, but some element in between. Runner-up is in
calculations for graphics code, mostly with respect to rounding errors
that result in off-by-one.

You are talking of the kind of off-by-one errors made by an experienced
programmer. I was talking of those made by a novice programmer.

Incorrect iteration termination is _way_ down on the list, and basically
never happens for experienced, competent programmers.

But does for novice programmers.

Arguing in favor of one indexing method or another as a preventative for
off-by-one errors is not, I feel, something supported by experience or
logical analysis of the situation.

You make it sound like I am advocating such a thing. I'm not. There are
many things in Java that are relatively hard to learn, that doesn't mean
I automatically want to change Java.

Just my two cents.

Ditto.
 
W

Wojtek

RedGrittyBrick wrote :
Yes, exactly. The programmer at hand is always more used to an index base of
1.

Hmmm, my first serious language used a base index of zero. I have
trouble converting to a base index of one.

Visual Basic is especially bad at this as some functions which return
arrays use a base index of zero whereas others return with a base index
of one. Where a "count" can return the highest index, or the number of
elements.

Plus the fun case where you can set index boundaries to some arbitrary
set of numbers

Dim Year(2000 to 2008)

where the base index is 2000.

Oh, and you can change the base index by using :
Option Base 1

and now the lowest index is 1, but ONLY for arrays set up IN THAT FILE!

I ALWAYS use LBound and UBound when walking an array in VB.

I have a belief that VB was written by many small teams who had no
chance of communicating with each other.

Um, yes (blushes), I do have to sometimes use alternate langauages.
Switching almost always causes me to commmit basic syntax errors for a
while.

Ok, rant off :)
 
A

Andreas Leitgeb

RedGrittyBrick said:
When people count the pennies in their pocket they count 1,2,3.

It's my lazyness: if I count my fingers from 0 to 9, I've saved
myself one digit! :)
That may be fun here, but with computers, starting with 0 means
being able to count one more (with some given number of bits use
able for counting) than when starting with 1, since
0 wouldn't work well to descibe "1 more than I can count to".

btw., iirc, gwbasic had a way for the user to choose, if arrays
(defined with "dim" shall start with 0 or 1 (I vaguely recall
"option base") Don't remember, what I used to choose back then.
Another reason may be that with a 1-based arrays you would iterate from
1 to n where n is the length. With zero-based arrays you iterate from 0
to n-1. Sometimes new programmers accidentally omit the -1 from the end
condition, because it is slightly unnatural.

I also omit any "-1" from the end condition, but I do it, because
I use "<", not "<=" to check against the wanted number of loops.
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top