-2

I'm trying to get familiarized with for loops right now for school and and learning the syntax right now. I have a couple questions. If I am going to initialize variables in the loop how can I ask the user for them to input the variable values before they are in the for loop? Here is the code I have written for it so far.

Also my scanner won't work for me in this code. I've been working on it for little bit so I figure it might need a second look.

import java.util.Scanner;


public class forloop
{
    public static void main(String []args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter your first of two numbers:");
        num1 = input.nextInt();
        System.out.print("Enter the second number:");
        num2 = input.nextInt();

        for(int num1 ; counter <= num2; counter ++)
        System.out.println("There are " + counter + " numbers between " + 
        num1 + " and " + num2);
    }
}

Thanks in advance for any help

jp89lawson
  • 17
  • 6

2 Answers2

0

You could assign the user's input into temporary variables and then inside your loops initialize the user's inputs to be those temporary variables.

import java.util.Scanner;


public class forloop
{
public static void main(String []args)
{
    Scanner input = new Scanner(System.in);

    System.out.print("Enter your first of two numbers:");
    int temp1 = input.nextInt();
    System.out.print("Enter the second number:");
    int num2 = input.nextInt();

    for(int num1 = temp1; counter <= num2; counter ++)
    System.out.println("There are " + counter + " numbers between " + 
    num1 + " and " + num2);
}

}

0

I think this is the simplest possible solution:

public class forloop
{
    public static void main(String []args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter your first of two numbers:");
        num1 = input.nextInt();
        System.out.print("Enter the second number:");
        num2 = input.nextInt();

        for(int x = num1 ; counter <= num2; counter ++)
        System.out.println("There are " + counter + " numbers between " + 
        num1 + " and " + num2);
    }
}

In the first expression in a for loop, you need to declare the variable that is controlling the loop and assign it a value - num1 in your case. In the second expression, you need to put the condition on which the loop keeps iterating - I am not really sure what you meant by counter. The problem is that this variable has not been declared. You need to declare it before you can use it.
What do you want your program to do?

Aemilius
  • 556
  • 1
  • 6
  • 13