Question

Hey Guys , I need help with this assignment: This component of the final exam will...

Hey Guys ,

I need help with this assignment:

This component of the final exam will have two data structures. The two data structures will be a stack and the other will be a hashmap. The hashmap object will be added to the stack every time the user picks an answer. The hashmap will have a key and value. The key will be the timestamp (system time when the user selected a choice) and the value will be the choice the user picked. For example, if the question was Buffalo vs. Pittsburgh and the user picked Buffalo at 10pm, then the timestamp (key) will be 10pm and the value would be Buffalo. This hashmap object will then be added to the stack. You will have a hashmap object for every answer to the questions.

Here what I did for java:

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;


class userNewChoices{
        private Scanner scan = new Scanner(System.in);
        private Stack<Map> answers = new Stack<Map>();


        
        
        public void close() {
                scan.close();
        }


        public String getChoices(String choice1, String choice2) {
                System.out.println();
                System.out.println("Please choose from the following options: ");
                System.out.println("#1" + choice1);
                System.out.println("#2" + choice2);
                System.out.println("Enter your choice here: ");


                String userChoice = scan.next();
                return userChoice;
        }
        public void userStack(String userChoice) {
                Map<String,String> map1=new HashMap<>();
                String timeStamp = new SimpleDateFormat("ss.mm.HH.dd.MM.yyyy").format(new Date());


                map1.put(timeStamp, userChoice);
                answers.push(map1);
        }
        public void printAnswerStack(){
                Iterator userChoiceMap = answers.iterator();
                System.out.println();
                System.out.println("User stacks are as fellowed ");
                System.out.println();
                while(userChoiceMap.hasNext()) {
                        System.out.println(userChoiceMap.next());
                }
        }
}


public class sportGames {
        public static void main(String args[])
        {
                
        }
}

I dont know where to go from here.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note:

- The code has been developed and tested on following platform:

1. Java openjdk version "1.8.0_242".

2. Linux Ubuntu OS.

- Feel free to add your queries in the comment section (if any).

Explanation:

- For demo purpose, I've asked user to enter choice (out of Buffalo/Pittsburgh) 5 times. You can choose your own implementation over it.

- For validation, I've created printUserAnswersStack() method that'll display hashmap contents inserted in stack.

Source code:

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;

class UserChoiceRecord{
   private Scanner scan = new Scanner(System.in);
   private Stack<Map> userAnswers = new Stack<Map>();

   // close Scanner object to avoid resource leak
   public void close(){
       scan.close();
   }

   // get user choice out of given 2 options
   public String getUserChoice(String choice1, String choice2){
       System.out.println();
       System.out.println("You have following options:");
       System.out.println("#1 " + choice1);
       System.out.println("#2 " + choice2);
       System.out.println("Enter your choice:");

       String userChoice = scan.next();

       return userChoice;
   }

   // create stack for the choices entered by user
   public void createUserChoiceStack(String userChoice){
       // record current timestamp. The timestamp will be in format yyyy.MM.dd.HH.mm.ss
       String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
       Map<String, String> userAnswer = new HashMap<String, String>();
      
       // create a key-value pair in hashmap
       userAnswer.put(timeStamp, userChoice);
      
       // push the hashmap contents into stack
       userAnswers.push(userAnswer);
   }

   // display the user choices from the stack
   public void printUserAnswersStack(){
       Iterator userChoicesMap = userAnswers.iterator();

       System.out.println();
       System.out.println("The user choices as in stack are as follows:");
       System.out.println();

       while(userChoicesMap.hasNext()){
           System.out.println(userChoicesMap.next());
       }
   }

   public static void main(String ...arg){
       UserChoiceRecord record = new UserChoiceRecord();
      
       // ask for user choice 5 times, create a singleton map from them and push that map into stack
       for(int i = 0; i < 5; ++i){
           record.createUserChoiceStack(record.getUserChoice("Buffalo", "Pittsburgh"));
       }
      
       // display the values pushed into the stack
       record.printUserAnswersStack();

       record.close();
   }
}


Attached are the code screenshots for your reference.

Sample output:

Add a comment
Know the answer?
Add Answer to:
Hey Guys , I need help with this assignment: This component of the final exam will...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need to add a method high school student, I couldn't connect high school student to...

    I need to add a method high school student, I couldn't connect high school student to student please help!!! package chapter.pkg9; import java.util.ArrayList; import java.util.Scanner; public class Main { public static Student student; public static ArrayList<Student> students; public static HighSchoolStudent highStudent; public static void main(String[] args) { int choice; Scanner scanner = new Scanner(System.in); students = new ArrayList<>(); while (true) { displayMenu(); choice = scanner.nextInt(); switch (choice) { case 1: addCollegeStudent(); break; case 2: addHighSchoolStudent(); case 3: deleteStudent(); break; case...

  • package rpsgamesimulation; import java.util.Random; import java.util.Scanner; /** * * @author cristy */ public class RPSGame {...

    package rpsgamesimulation; import java.util.Random; import java.util.Scanner; /** * * @author cristy */ public class RPSGame { private String userChoice, computerChoice;    public RPSGame() { userChoice = "rock"; computerChoice = "rock"; }    public String getUserChoice() { return userChoice; }    public String getComputerChoice() { return computerChoice; }    public void setUserChoice(String aUserChoice) { userChoice = aUserChoice; }    public void setComputerChoice(String aComputerChoice) { computerChoice = aComputerChoice; }    public String toString() { return "User Choice: " + userChoice + "...

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • In Java, write JUnit tests to verify various question-type objects for the following below: public interface...

    In Java, write JUnit tests to verify various question-type objects for the following below: public interface IAnswer {    public String getAnswer();    } import java.util.Scanner; YesNo class: public class YesNo implements IAnswer{            private String question;            public YesNo(String q){                this.question = q;            }                       //This function returns question text            public String getQuestionText() {                return question;...

  • I have most of the code for this assignment but need some help getting the rest....

    I have most of the code for this assignment but need some help getting the rest. Go to bottom to see what I have. Please help me figure out the foreach loops and the put() statement. In this assignment, you will be using a new data structure, HashMaps, to repeat Assignment 8.3. Main Method (5 points) Declare and initialize an HashMap with values of type of type Employee, and keys of type integer. In a while loop, keep initializing objects...

  • // can someone explain the code line by line shortly.thanks import java.security.KeyPair; import ...

    // can someone explain the code line by line shortly.thanks import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Base64; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; // Java 8 example for RSA encryption/decryption. // Uses strong encryption with 2048 key size. public class GlobalMembers { public static void main(String[] args) throws Exception { String plainText = "Hello World!"; // Generate public and private keys using RSA Map<String, Object> keys = getRSAKeys(); PrivateKey privateKey = (PrivateKey) keys.get("private"); PublicKey publicKey = (PublicKey)...

  • Modify the below Java program to use exceptions if the password is wrong (WrongCredentials excpetion). import java.util....

    Modify the below Java program to use exceptions if the password is wrong (WrongCredentials excpetion). import java.util.HashMap; import java.util.Map; import java.util.Scanner; class Role { String user, password, role; public Role(String user, String password, String role) { super(); this.user = user; this.password = password; this.role = role; } /** * @return the user */ public String getUser() { return user; } /** * @param user the user to set */ public void setUser(String user) { this.user = user; } /** *...

  • I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public...

    I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public static void main(String[] args) {         if (args.length !=1) {             System.out.println(                                "Usage: java wordcount2 fullfilename");             System.exit(1);         }                 String filename = args[0];               // Create a tree map to hold words as key and count as value         Map<String, Integer> treeMap = new TreeMap<String, Integer>();                 try {             @SuppressWarnings("resource")             Scanner input = new Scanner(new File(filename));...

  • (JAVA) I need to write an accessor method for the employeeDatabase field. The method is supposed...

    (JAVA) I need to write an accessor method for the employeeDatabase field. The method is supposed to be named getEmployeeDatabase() and have a return type of Hashmap<Integer,Employee>. I have also included the test case below that is being used for this code to see if it works properly private HashMap<Integer, Employee> employeeDatabase; public CompanyO f Scanner employeeDatabasepopulateEmployeeDatabase(keyboard) keyboard - new Scanner(System.in); public static void main(String[ args) private HashMap<Integer, Employee> populateEmployeeDatabase(Scanner keyboard) int numobjects -keyboard.nextIntO; String words HashMap <Integer, Employee mapnew...

  • Write one JUnit test in Java for the following: Essay class: import java.util.Scanner; public class Essay implements IAn...

    Write one JUnit test in Java for the following: Essay class: import java.util.Scanner; public class Essay implements IAnswer{ private String question; public Essay(String q){ this.question = q; } //This function returns question text public String getQuestionText() {    return question; } //This function takes answer from user public void answer(String userAnswer) {    // Take care of answer } @Override public String getAnswer() { System.out.println(question); Scanner scan = new Scanner(System.in); System.out.print("Answer: "); String ans =scan.nextLine(); scan.close(); if(ans.length() <=140){ return ans; }else{ return...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT