Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

java - Create dynamic templated message based on a list

this is easy in JavaScript. Not sure how to do this in Java:

Here's the hash table that's sent into displayItems:

Hashtable<Integer, String> items = new Hashtable<Integer, String>();
items.put(0, "Soda");
items.put(1, "Candy");
items.put(2, "Fruit");

Now here's what I'm trying to do, create a message based on that list:

 public void displayItems(Hashtable<Integer, String> items) {
    String message = "Please specify an item: ";
    items.forEach((itemIndex, itemName) -> {
      message += `${itemIndex}: ${itemName},`;
    });
    outputStream.print(message);
  }

What I want to end up with printed to the stream for message is this:

"Please specify an item: 0: Soda, 1: Candy, 2: Fruit"
question from:https://stackoverflow.com/questions/66055906/create-dynamic-templated-message-based-on-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The other answer works but here is a standard solution if you want to keep your displayItems function and Hashtable.

Hashtable<Integer, String> items = new Hashtable<Integer, String>();
items.put(0, "Soda");
items.put(1, "Candy");
items.put(2, "Fruit");
    
displayItems(items);

public static void displayItems(Hashtable<Integer, String> items) {
   String message = "Please specify an item: ";
   for(int i = 0; i < items.size(); ++i) {
       message += String.valueOf(i) + ": " + items.get(i);
       if(i+1 < items.size()) message += ", ";
   }
   System.out.println(message);
}

Output:

Please specify an item: 0: Soda, 1: Candy, 2: Fruit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...