Question

In: Computer Science

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.TreeSet; /** * MapSetLab - test the...

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.TreeSet;

/**
 * MapSetLab - test the HashMap and TreeSet classes.
 * 
 * @author Michael Norton
 * @version 18 September 2018
 */
public class MapSetLab {
    
    /**
     * Main method.
     * 
     * @param args The command line arguments
     * @throws IOException The IOException
     */
    public static void main( String[] args ) throws IOException {
        
        // declarations & some instantiations
        BufferedReader reader = new BufferedReader( new InputStreamReader( 
                        System.in ) );
        HashMap< String, TreeSet< String > > networkMap = 
                        new HashMap< String, TreeSet< String> >();

        // reusable references
        String network;
        String tvShow;
        TreeSet< String > set;
        
        // get 10 network & tv show pairs
        for ( int i = 0; i < 10; i++ ) {
            
            // get values from user
            System.out.print(  "Enter TV network: " );
            network = reader.readLine();
            System.out.print( "Enter TV show on " + network + ": " );
            tvShow = reader.readLine();
            
            // if key not found, create new entry
            if ( !networkMap.containsKey( network ) ) {
                
                networkMap.put( network, new TreeSet<String>() );
            }
            
            // get the TreeSet from the HashMap and add the show to the network
            set = networkMap.get( network );
            set.add( tvShow );
            
            // print out the mapping
            System.out.println( networkMap );
            System.out.println();
        }
        
    }

}

Use an appropriate loop to ask the user to enter the name of a TV show and then print on a separate line the name of the network that maps to that show. Repeat until the user enters an empty string.

HINT: Iterate over each key (network) in the HashMap, and see if its value (set of shows) contains the desired show. If so, print out the network. If none of the networks have that show, report "UNKNOWN". You don't have to worry about uppercase/lowercase, just match the TV show name exactly.

Solutions

Expert Solution

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.HashMap;

import java.util.TreeSet;

/**

* MapSetLab - test the HashMap and TreeSet classes.

*

* @author Michael Norton

* @version 18 September 2018

*/

public class MapSetLab {

       /**

     * Main method.

     *

     * @param args The command line arguments

     * @throws IOException The IOException

     */

      

       public static void main(String[] args) throws IOException {

                // declarations & some instantiations

        BufferedReader reader = new BufferedReader( new InputStreamReader(

                        System.in ) );

        HashMap< String, TreeSet< String > > networkMap =

                        new HashMap< String, TreeSet< String> >();

        // reusable references

        String network;

        String tvShow;

        TreeSet< String > set;

       

     // get 10 network & tv show pairs

        for ( int i = 0; i < 10; i++ ) {

           

            // get values from user

            System.out.print( "Enter TV network: " );

            network = reader.readLine();

            System.out.print( "Enter TV show on " + network + ": " );

            tvShow = reader.readLine();

           

            // if key not found, create new entry

            if ( !networkMap.containsKey( network ) ) {

               

                networkMap.put( network, new TreeSet<String>() );

            }

           

            // get the TreeSet from the HashMap and add the show to the network

            set = networkMap.get( network );

            set.add( tvShow );

           

            // print out the mapping

            System.out.println( networkMap );

            System.out.println();

           

        }

       

        boolean found ;

        // loop that continues till the user exits

        while(true)

        {

             found = false;

             // input of tv show name

             System.out.print("Enter the TV show name : ");

             tvShow = reader.readLine();

             // check if user entered an empty string, then exit from loop

             if(tvShow.length() == 0)

                    break;

             // loop over the map

             for( String tvNetwork: networkMap.keySet())

             {

                    // check if this network contains the tv show, then print the network and exit from loop

                    if(networkMap.get(tvNetwork).contains(tvShow))

                    {

                           System.out.println(tvNetwork);

                           found=true;

                           break;

                    }

             }

            

             // check if tv show network was found, if not print "UNKNOWN"

             if(!found )

                    System.out.println("UNKNOWN");

        }

       

        reader.close();

       }

}

//end of MapSetLab.java

Output:


Related Solutions

HW1 code sample.fxml <?import javafx.geometry.Insets?> <?import javafx.scene.layout.GridPane?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <?import javafx.scene.layout.ColumnConstraints?> &lt
HW1 code sample.fxml <?import javafx.geometry.Insets?> <?import javafx.scene.layout.GridPane?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <?import javafx.scene.layout.ColumnConstraints?> <?import javafx.scene.control.TextField?> <?import javafx.scene.layout.HBox?> <?import javafx.scene.control.ToggleGroup?> <?import javafx.scene.control.RadioButton?> <?import javafx.scene.control.CheckBox?> <?import javafx.scene.control.ComboBox?> <?import javafx.collections.*?> <?import java.lang.String?> <?import javafx.collections.FXCollections?> <?import javafx.collections.FXCollections?> <?import javafx.scene.text.Font?> <GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="TOP_CENTER" hgap="10" vgap="10"> <columnConstraints> <ColumnConstraints percentWidth="50"/> <ColumnConstraints percentWidth="50"/> </columnConstraints> <padding> <Insets topRightBottomLeft="5"/> </padding> <Label GridPane.rowIndex="0" GridPane.columnIndex="0" text="Name"> </Label> <Label GridPane.rowIndex="1" GridPane.columnIndex="0" text="Street" > </Label> <Label GridPane.rowIndex="2" GridPane.columnIndex="0" text="City"> </Label> <Label GridPane.rowIndex="3" GridPane.columnIndex="0" text="State" > </Label> <Label GridPane.rowIndex="4" GridPane.columnIndex="0" text="Zip" > </Label> <Label...
In Java please Cipher.java: /* * Fix me */ import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import...
In Java please Cipher.java: /* * Fix me */ import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class Cipher { public static final int NUM_LETTERS = 26; public static final int ENCODE = 1; public static final int DECODE = 2; public static void main(String[] args) /* FIX ME */ throws Exception { // letters String alphabet = "abcdefghijklmnopqrstuvwxyz"; // Check args length, if error, print usage message and exit if (args.length != 3) { System.out.println("Usage:\n"); System.out.println("java...
import java.util.LinkedList; import java.util.Queue; import java.time.*; public class CheckOutLine { /** This is the main function...
import java.util.LinkedList; import java.util.Queue; import java.time.*; public class CheckOutLine { /** This is the main function for the program */ public static void main() { System.out.println("\n\tBegin CheckOutLine Demo\n"); System.out.println("\nCreating a Queue called \"register\" based on a LinkedList"); Queue<Customer> register = new LinkedList<Customer>();    System.out.println("\nAdding Customers to the Register queue"); // 1. TO DO: add five or more customers to the register line (5 Pts) // format: register.add(new Customer(name, checkout time));                System.out.printf("Register line has %d customers\n",...
This is Java Programing. Add a shape of oval to BOXBALLOVAL. import java.awt.*; import java.awt.event.*; import...
This is Java Programing. Add a shape of oval to BOXBALLOVAL. import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.Timer; import javax.swing.*; public class BOXBALLOVAL {    public static void main(String[] args) { new myframe();// creating main jframe instance    } } class myframe extends JFrame {    Container c;    JPanel panel;    JButton addbutton, removebutton;    JLabel counter, ballsize;    JTextField size_input;    JComboBox cb;    buttonListener handle;    myDrawboard myboard;    JFrame mainFrame;    public myframe()    {...
import java.util.ArrayList; import java.util.Collections; import java.lang.Exception; public class ItemList { /** This is the main process...
import java.util.ArrayList; import java.util.Collections; import java.lang.Exception; public class ItemList { /** This is the main process for the project */ public static void main () { System.out.println("\n\tBegin Item List Demo\n"); System.out.println("Declare an ArrayList to hold Item objects"); ArrayList<Item> list = new ArrayList<Item>(); try { System.out.println("\n Add several Items to the list"); list.add(new Item(123, "Statue")); list.add(new Item(332, "Painting")); list.add(new Item(241, "Figurine")); list.add(new Item(126, "Chair")); list.add(new Item(411, "Model")); list.add(new Item(55, "Watch")); System.out.println("\nDisplay original Items list:"); listItems(list); int result = -1; // 1....
Implement a Factory Design Pattern for the code below: MAIN: import java.util.ArrayList; import java.util.List; import java.util.Random;...
Implement a Factory Design Pattern for the code below: MAIN: import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { public static void main(String[] args) { Character char1 = new Orc("Grumlin"); Character char2 = new Elf("Therae"); int damageDealt = char1.attackEnemy(); System.out.println(char1.name + " has attacked an enemy " + "and dealt " + damageDealt + " damage"); char1.hasCastSpellSkill = true; damageDealt = char1.attackEnemy(); System.out.println(char1.name + " has attacked an enemy " + "and dealt " + damageDealt + " damage");...
This is the code that needs to be completed... import java.util.ArrayList; import java.util.Collections; /** * Write...
This is the code that needs to be completed... import java.util.ArrayList; import java.util.Collections; /** * Write a description of class SpellChecker here. * * @author (your name) * @version (a version number or a date) */ public class SpellChecker { private ArrayList words; private DictReader reader; /** * Constructor for objects of class SpellChecker */ public SpellChecker() { reader = new DictReader("words.txt"); words = reader.getDictionary(); } /** * This method returns the number of words in the dictionary. * Change...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME =...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME = "bowler.txt"; public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading Data from file"); Scanner fileReader = new Scanner(new File(FILE_NAME)); System.out.printf("%-20s%-10s%-10s%-10s%-10s\n", "Sample Data", "Game 1", "Game 2", "Game 3", "Average"); int bowler = 1; while (fileReader.hasNext()) { String scores[] = fileReader.nextLine().split("\\s+"); double average = Integer.parseInt(scores[0]) + Integer.parseInt(scores[1]) + Integer.parseInt(scores[2]); average /= 3; System.out.printf("%-20s%-10s%-10s%-10s%-10.2f\n", "Bowler " + bowler, scores[0], scores[1], scores[2], average); bowler += 1; }...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
Are Import Quotas with no Licensing fee more inefficient that an import quota that has a...
Are Import Quotas with no Licensing fee more inefficient that an import quota that has a licensing fee that only takes a portion of the foreign gains?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT