RyRy RyRy - 1 month ago 9
Java Question

ways to Java for Loops

Hi I am just really confused on how to ask the user for a starting number and an ending number.

Use the for loop to iterate through the range of integers.

Display:

list of even numbers in that range
the number of even numbers displayed

import java.util.Scanner;

public class Assignment8 {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner keyboard = new Scanner(System.in);
int count;
int end;
int start;

System.out.println("Enter the starting number");
start = keyboard.nextInt();
System.out.println("Enter the ending number");
end = keyboard.nextInt();

for(int count=start; count <= end; count++){

if( count % 2 == 0){
System.out.print(i + " ");
System.out.println("Enter the next number");
i = keyboard.nextInt();

}
}
}
}


This is what i got so far but I don't know how to start a list, and to count them.

I just don't understand how it is done it is not a certain amount the user can do as many numbers as they want or any number.

Answer

Try to make your code as follows:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MainApp {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        int end;
        int start;
        List<Integer> evenNumbers = new ArrayList<Integer>();

        System.out.println("Enter the starting number");
        start = keyboard.nextInt();
        System.out.println("Enter the ending number");
        end = keyboard.nextInt();

        for (int i = start; i <= end; i++) {

            if (i % 2 == 0) {
                evenNumbers.add(i);
            }
        }

        System.out.println("There are " + evenNumbers.size() + " even numbers between [" +start +"," + end + "]");
        System.out.println("The numbers are: " + evenNumbers.toString());

    }
}

If you need the numbers between the start and the end change the for loop as follows:

i++
for (int i = start; i < end; i++)
Comments