You want to do that with a loop counter, let it be i
:
for (int i = a; i <= z; i++) {
//process i
}
In this way you have i
that starts at a
and increases up to z
.
Question
Easy question (I'm a beginner!)... My java program needs to refer back to the user-entered integers stored as variables "a" and "z". These two variables are initialized using a Scanner and the nextInt() method. Here's my code:
Scanner in = new Scanner(System.in);
int a;
int z;
int x;
System.out.println("Please provide a lower bound (integer): ");
a = in.nextInt();
System.out.println("Please provide an upper bound (integer): ");
z = in.nextInt();
So now I need to refer back to these user-entered variables in a for-loop that appears later on, but I do not know the syntax to do this. I need the for-loop to start at "a" and continue one-by-one until "z".
for(a ; a <= z ; a++) {
//code irrelevant to my question
}
Java is making it very clear that I cannot just write the variables in the for-loop, so how do I do it? Thanks!
Solution
You want to do that with a loop counter, let it be i
:
for (int i = a; i <= z; i++) {
//process i
}
In this way you have i
that starts at a
and increases up to z
.
OTHER TIPS
To start at a and end on z, inclusive:
for(; a <= z ; a++) {
To stop right before z:
for(; a < z ; a++) {
This will change the variable a
.
You don't need to fill that space before the first semi-colon. That's the "initialize counter" spot, and you've already initialized your counter from user input above (before) the loop.
If you don't want a
to change, then simply duplicate its value into a temporary one, as in @skiwi's answer:
for(int i = a; i <= z; i++) {
Here's some good information: https://www.google.com/search?q=for+loop+java
If you want to include z:
for(int i=a;i<=z;i++){
[stuff]
}
or, if you want it to exclude z:
for(int i=a;i<z;i++)
[stuff]
}
This is because the format for for loops is for(int [counter]=[start value];[counter][condition][limit];[counter][change amount])
. For example, if you wanted something to loop up to (including) two, including zero, your code would be for(int i=0; i<3;i++)
, while if you wanted it to loop down from two to zero it would be for(int i=2; i>=0;i--)
.
To make the loop skip values just change the amount the counter increases/decreases by, such as i+=2
, or i-=2
Existing answers tell you how to fix it, but don't explain what the problem is. If you try to compile the class, you'll see the following error
$ javac SomeClass.java
SomeClass.java:16: error: not a statement
for(a ; a <= z ; a++) {
^
That's because a
by itself is not a statement.
The simplest thing is to just omit the a
since you don't need to initialize it
for(; a <= z ; a++) {}
Alternatively, you could create a looping variable so you don't affect a
and you can initialize it in the loop so it looks more like a normal loop.
for(int i = a; i <= z ; i++) {}