I'm trying to create a counter controlled while loop. Currently I'm having difficulty getting the counter to increase by 1 for each pass through off the loop.
I set my code to
int numberCounter = 0; // Numbers 0 through 10.
String head1 = "Number: " + numberCounter;
String head2 = " Multiplied by 2: " + numberCounter * 2;
String head3 = " Multiplied by 10: " + numberCounter * 10;
int byTwo; // Stores the number multiplied by 2.
int byTen; // Stores the number multiplied by 10.
final int NUM_LOOPS = 11; // Constant used to control loop.
// This is the work done in the housekeeping() method
System.out.println("Numbers 0 through 10 multiplied by 2 and by 10" + "\n");
System.out.println(head1 + head2 + "\n");
System.out.println(head1 + head3 + "\n");
while (numberCounter != 10) numberCounter = numberCounter + 1;
System.out.println(head1 + head2 + "\n");
System.out.println(head1 + head3 + "\n");
but it just reads the 0 value and exits after one pass.
I expect each pass to add one to the counter, but it seems to stay at 0. I say that because the output reads:
Numbers 0 through 10 multiplied by 2 and by 10
Number: 0 Multiplied by 2: 0
Number: 0 Multiplied by 10: 0
Number: 0 Multiplied by 2: 0
Number: 0 Multiplied by 10: 0
numberCounter
doesn't start with the value 10), you need to show us more of your code to see what goes wrong. – Joachim Sauer Nov 11 '19 at 15:39for
loop? – charles-allen Nov 11 '19 at 15:51String head1 = "Number: " + numberCounter;
and later you change value ofnumberCounter
then data held byhead1
should also change/update. That is not true. Value of string is decided at time of its creation and never changes. Just like when you haveint a =1;
and later you writeint b = a;
yourb
will hold its own copy of value 1 which was held ina
at that time. Even when you later assign toa
some other value likea=3;
b
would still hold its own copy of 1. – Pshemo Nov 11 '19 at 16:25