Home >Backend Development >C++ >How Can I Randomly Select and Display an Element from an ArrayList?

How Can I Randomly Select and Display an Element from an ArrayList?

DDD
DDDOriginal
2025-01-19 14:42:11303browse

How Can I Randomly Select and Display an Element from an ArrayList?

Randomly Accessing and Displaying List Items

This guide demonstrates how to select and display a random string from an ArrayList in response to a button click. Follow these steps:

  1. Create a Random Number Generator:
<code>static Random rnd = new Random();</code>
  1. Generate a Random Index:
<code>int randomIndex = rnd.Next(list.Count);</code>
  1. Retrieve the String:
<code>string selectedString = list[randomIndex];</code>
  1. Display the Result:
<code>MessageBox.Show(selectedString);</code>

This method ensures a random string from the ArrayList is retrieved and displayed within a message box.

The above is the detailed content of How Can I Randomly Select and Display an Element from an ArrayList?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn