gpt4 book ai didi

java - 从 ArrayList 到 Hashmap

转载 作者:行者123 更新时间:2023-12-02 03:30:55 27 4
gpt4 key购买 nike

我是 Java 新手,正在尝试使用下面的工作代码并将我的 ArrayList 转换为 Hashmap。我感到困惑,因为它们根本不同。由于 HashMap 使用键/值对,我不太明白,鉴于我已经在工作的程序,我会这样做。抱歉,如果这是一个愚蠢的问题,我想我对我需要做什么感到困惑。

这是我使用 ArrayList 的类:

感谢您的帮助。

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;

}

}

这是我的主课:

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");


}

}

最佳答案

我假设您将使用 ArrayList 中元素的索引作为键,并将数组中的实际元素作为 HashMap 中的值。

希望有帮助!

关于java - 从 ArrayList 到 Hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com