We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1
import java.util.
PriorityQueue; import java.util.Scanner;
public class Greetings {
public static void main(String[] args) {
// Create a scanner for reading user input from the console Scanner scanner = new Scanner(System.in);
// Create a PriorityQueue to store nicknames alphabetically
PriorityQueue<String> nicknames = new PriorityQueue<>();
// Prompt the user to enter the nicknames of 8 classmates
System.out.println("Enter the nicknames of 8 of your classmates:"); for (int i = 0; i < 8; i++) { String nickname = scanner.nextLine();
// Check if the input contains only letters
if (nickname.matches("[a-zA-Z]+")) { nicknames.offer(nickname); // Add valid nickname to the queue } else { System.out.println("Invalid input. Please enter a nickname containing only letters."); i--; // Decrement i to re-prompt for a valid nickname input } }
// Prompt to start greeting classmates by pressing 'H'
System.out.println("Press 'H' to say 'Hi' to each classmate. Press any other key to exit.");
// Loop to greet each classmate until the queue is empty
while (!nicknames.isEmpty()) { String input = scanner.next(); // Read input from user
// Check if input is 'H' (case-insensitive) to say 'Hi' to a classmate
if (input.equalsIgnoreCase("H")) { System.out.println("Hi " + nicknames.poll() + "!"); // Greet the next classmate in alphabetical order } else { System.out.println("Invalid input. Please press 'H' to say 'Hi' or any other key to exit."); } }
// Once all nicknames are greeted, print a completion message