You are to write a program name array_list.java that will do the following: Crea
ID: 3759833 • Letter: Y
Question
You are to write a program name array_list.java that will do the following:
Create an ArrayList data structure that will hold Integer values.
Prompt the user for a number that is greater than 50 which will be the number of items you will place into this ArrayList data structure you created.
Generate this amount of random number (the random numbers should range from 1 to 100) one at a time and insert this number (one at a time) into the ArrayList.
These numbers are to be inserted in sequential order (i.e. from smallest to largest). For example if you already have 3 numbers in the list as in 3, 6, 8 and your next randomly generated number is 5, your new list must be 3, 5, 6, 8 before you even generate another random number, and so on and so on.
After you are finished, display the entire content of the ArrayList on the screen.
Remember --- DO NOT GENERATE ALL THE NUMBERS BEFORE STARTING TO INSERT INTO THE LIST AND DO NOT USE ANY SORTING ROUTINE FROM THE LIBRARY TO SORT THE ArrayList.
Explanation / Answer
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Create new ArrayList.
ArrayList<Integer> elements = new ArrayList<>();
// Add three elements.
elements.add(10);
elements.add(15);
elements.add(20);
// Get size and display.
int count = elements.size();
System.out.println("Count: " + count);
// Loop through elements.
for (int i = 0; i < elements.size(); i++) {
int value = elements.get(i);
System.out.println("Element: " + value);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.