201k views
0 votes
Write the statements to prompt the user to enter dog names and cat names. Each line of input contains d (dog) or c (cat) followed by the name. The user will enter q quit when done. Print out all the cat names followed by all the dog names. The cat names and the dog names must be output in the same order in which they were entered. Use LinkedQueue objects in your code.

1 Answer

4 votes

Answer:

see explaination

Step-by-step explanation:

import java.util.*;

import java.util.concurrent.*;

class Main {

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in); //Scanner Object to read Input

//LinkedQueue of String Type

ConcurrentLinkedQueue<String> cat_queue = new ConcurrentLinkedQueue<String>();

ConcurrentLinkedQueue<String> dog_queue = new ConcurrentLinkedQueue<String>();

System.out.println("Enter Dog names and Cat names\\");

//Reading input until line exists

while(sc.hasNextLine()){

String s = sc.nextLine(); //Reading string

String[] arr = s.split("\\s+"); //Splitting the string based on spaces

if (arr[0].equals("q") && arr[1].equals("quit")){ //checking if q quit or not

//printing cats and dogs if q quit

System.out.println("\\cats:");

//printing each cat_name in seperate line

for (String cat_name : cat_queue) { //Iterating over elements in cat_queue

System.out.println(cat_name);

}

System.out.println("\\dogs:");

//printing each dog_name in seperate line

for (String dog_name : dog_queue) { //Iterating over elements in dog_queue

System.out.println(dog_name);

}

System.exit(0); //Exiting as q quit is entered

}

else{

if(arr[0].equals("c")){ //If c is the string entered before name

cat_queue.add(arr[1]); //Add the cat_name into cat_queue

}

else if(arr[0].equals("d")){ //If d is is the string entered before name

dog_queue.add(arr[1]); //Add the dog_name into dog_queue

}

}

}

}

}

see attachment for screenshot of the code and output

Write the statements to prompt the user to enter dog names and cat names. Each line-example-1
Write the statements to prompt the user to enter dog names and cat names. Each line-example-2
User Rebecca Meritz
by
5.3k points