How to reference an int entered by the user?

advertisements

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!


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.