I am new to Java and am trying to take the below working code and convert my ArrayList to a Hashmap. My confusion comes in because they are so fundamentally different. Since the hashmap using key/value pairs I am not quite understanding I do this given the program I have working already. Sorry if it is a stupid question, I think I am confused about what I need to do.
This is the class where I am using the ArrayList:
Thank you for any help.
import java.util.ArrayList;
import java.util.Scanner;
//new class ArrayMessage
public class ArrayMessage {
//new method shoutOutCannedMethod returning a String
public String shoutOutCannedMessage() {
// create some variables
int arraySize = 10;
String displayUserMessage = "";
String userMessage = "";
String goAgain = "yes";
// setup scanner to store input
Scanner input = new Scanner(System.in);
// create arrayList
ArrayList<String> message = new ArrayList<String>();
// start loop
while (!goAgain.equals("no")) {
// clear out arrayList
message.clear();
// ask the user for 10 messages as long as the counter is less than
// the size of the array
for (int counter = 0; counter < arraySize; counter++) {
System.out.printf(counter + 1 + ": Please enter a message: ");
// save user message to userMessage
userMessage = input.nextLine();
// add users message to arraylist
message.add(userMessage);
}
// ask the user if they want to to load different messages into
// arraylist
System.out.print("Messages have been loaded? Would you like to reload? Type 'yes' or 'no': ");
goAgain = input.nextLine(); // store input
}
// ask the user to choose which message they want displayed
System.out.print("Please enter the number of the message you would like displayed: ");
userMessage = input.nextLine();
// store users message into variable to be used later
displayUserMessage = message.get(Integer.parseInt(userMessage) - 1);
input.close();
// return userMessage
return displayUserMessage;
}
}
This is my main class:
public class ShoutBox {
//main method
public static void main(String[] args) {
//call ArrayMessage class
ArrayMessage myMessage = new ArrayMessage();
//call shoutOutCannedMessage method
String userMessage = myMessage.shoutOutCannedMessage();
// display message selected by user
System.out.printf("Your selected value is " + userMessage + "\n");
}
}