1. Write a program to accept inputs (10 numbers in a type int or double ) from t
ID: 3547744 • Letter: 1
Question
1. Write a program to accept inputs (10 numbers in a type int or double) from the user at the command line, and store in an ArrayList. (40 points)
1) These numbers must be inputted at the command line.
2) These numbers should be store in an ArrayList.
3) Find the large number in the list and display it.
4) Insert an element to the list at position 3.
5) Remove an element from the list at position 5.
6) Replace the value in the list at position 2
7) Display the new list.
Write a program to accept inputs (10 numbers in a type int or double) from the user at the command line, and store in an ArrayList. These numbers must be inputted at the command line. These numbers should be store in an ArrayList. Find the large number in the list and display it. Insert an element to the list at position 3. Remove an element from the list at position 5. Replace the value in the list at position 2 Display the new list.Explanation / Answer
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class CheggArrayList
{
public static void main(String[] args)
{
ArrayList arr = new ArrayList();
Scanner input = new Scanner(System.in);//These numbers must be inputted at the command line.
String line ="";
for (int i = 0; i < 10;)
{
System.out.println("Please enter " + (i + 1)// These numbers must be inputted at the command line.
+ ". number(Double or Integer)");
line = input.nextLine();
try{
arr.add(Integer.parseInt(line));//Integer
i++;
}catch(Exception e){
try{
arr.add((int)Double.parseDouble(line));//Double values cast to int again for comparing end of the process
i++;
}catch(Exception e2){
System.out.println("Please try again unknown type (Double or Integer Only)!!!");
continue;
}
}
}
System.out.println("Largest Number: " + Collections.max(arr));// Find the large number in the list and display it.
arr.add(3, 15);// Insert an element to the list at position 3.
arr.remove(5);// Remove an element from the list at position 5.
arr.set(2, 65);// Replace the value in the list at position 2
System.out.println("New List: " + arr);// Display the new list.
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.