From 730b4086e58a6aa4693083a646a0cdf7478665c6 Mon Sep 17 00:00:00 2001 From: Alex Date: Tue, 25 Feb 2025 12:45:38 -0800 Subject: [PATCH] Add Q2.java --- Q2.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Q2.java diff --git a/Q2.java b/Q2.java new file mode 100644 index 0000000..624778d --- /dev/null +++ b/Q2.java @@ -0,0 +1,31 @@ +// Question 1 +// Import the LinkedHashMap and Scanner +import java.util.ArrayList; +import java.util.Scanner; + + +public class Main { + public static void main(String[] args) { + // Arraylist to store names, then we will use ArrayList.sort() to sort them + ArrayList names = new ArrayList<>(); + // Scanner object for user input + Scanner scanner = new Scanner(System.in); + + // Ask for the 3 names, then append to the ArrayList + System.out.println("Enter the first name: "); + names.add(scanner.nextLine()); + System.out.println("Enter the second name: "); + names.add(scanner.nextLine()); + System.out.println("Enter the third name: "); + names.add(scanner.nextLine()); + + // Use sort method. Null will have the arrays be sorted naturally by their data type, so alphabetially for string + names.sort(null); + + // Print out names, ascending sorted order + System.out.println("Names sorted in Ascending Order: "); + for(int i = 0; i < 3; i++) { + System.out.println(i+1 + ": " +names.get(i)); + } + } +} \ No newline at end of file