Write a program that adds the numbers 10, 15, 20, 25, 30 into the numbers ArrayList and…
- User
Write a program that adds the numbers 10, 15, 20, 25, 30 into the numbers ArrayList and then prints out the first element in the list.import java.util.ArrayList;
public class Numbers { public static void main(String[] args) { ArrayList numbers = new ArrayList();
// Add 5 numbers to `numbers` // Print out the first element in `numbers` }}
- Assistant
import java.util.ArrayList; public class Numbers { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>(); // Adding 5 numbers to `numbers` numbers.add(10); numbers.add(15); numbers.add(20); numbers.add(25); numbers.add(30); // Printing out the first element in `numbers` if (!numbers.isEmpty()) { // Checking if the list is not empty System.out.println(numbers.get(0)); } else { System.out.println("The list is empty."); } } }This program first initializes an
ArrayListofIntegertype. Then, it adds five numbers (10, 15, 20, 25, and 30) to theArrayList. After that, it checks if the list is not empty to ensure there is at least one element to print. If the list is not empty, it prints the first element of the list usingnumbers.get(0). - User
Create an ArrayList with elements that are even numbers from 100 - 300.
Hint: Use a loop!
import java.util.ArrayList;
public class Evens { public static void main(String[] args) { // Create the evens ArrayList
printArray(evens); } //Don't alter this method! It will print your array in the console public static void printArray(ArrayList<Integer> array) { System.out.println("Array:"); for(int name: array) { System.out.print(name + " "); } }}
- Assistant
To create an
ArrayListwith elements that are even numbers from 100 to 300, you can use a loop to iterate through this range, check if a number is even, and add it to theArrayList. Below is the modifiedEvensclass accordingly:import java.util.ArrayList; public class Evens { public static void main(String[] args) { ArrayList<Integer> evens = new ArrayList<Integer>(); // Loop from 100 to 300 (inclusive) for (int i = 100; i <= 300; i++) { // Check if the number is even if (i % 2 == 0) { evens.add(i); // Add even number to the ArrayList } } printArray(evens); } //Don't alter this method! It will print your array in the console public static void printArray(ArrayList<Integer> array) { System.out.println("Array:"); for(int number: array) { System.out.print(number + " "); } } }This program initializes an named to store the integers. It then uses a loop to iterate over integers from 100 to 300. Within the loop, it checks if an integer is even by checking if the remainder when is divided by 2 is 0 (using the condition). If is even, it is added to the using the method. Finally, it calls the method to print the even numbers added to the .