Add Q2.java
This commit is contained in:
31
Q2.java
Normal file
31
Q2.java
Normal file
@@ -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<String> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user