iT邦幫忙

DAY 10
3

看範例學C#系列 第 10

看範例學C#-10 陣列應用

這是一個隨機產生7個樂透號碼的範例
本例使用for 迴圈把42個號碼 塞到loto陣列中
並用Random隨機取值,然後再利用一個for迴圈去產生7個1~42 間不重覆的數字
每個數字間以,做分隔,並用Substring 方法 去掉最後一個逗號
s.Substring(0, s.Length - 1);//從第0個位置算起,s.Length –1 即為總長度減1,所以能把最後一個逗號消掉
String.Substring 方法請參考MSDN
String.Substring 方法 (Int32, Int32)
從這個執行個體擷取子字串。子字串起始於指定的字元位置,並且具有指定的長度。
以下為程式碼及註解

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ex10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string s = "";
            int[] loto = new int[42]; //將所有號碼(1~42)放入陣列loto中
            for (int i = 0; i <= 41; i++)
            {
                loto[i] = i + 1;
            }
            int[] x = new int[7]; //宣告要取多少個數字
            Random r = new Random();
            for (int j = 0; j <= 6; j++)
            {
                int temp = r.Next(1, 42); //隨機抓取一組數字放入x[]陣列中
                if (loto[temp] == 0) { j--; }//如果數字為0,則重新產生亂數
                else
                {
                    x[j] = loto[temp]; //否則將亂數產生之數字放入x[]陣列中
                    s += x[j].ToString() + ",";//每個數字以,分隔
                    loto[temp] = 0; //將以使用之數字以零取代
                    textBox1.Text = s.Substring(0, s.Length - 1);//去除最後一個逗號
                    if (j == 6)
                    {
                        MessageBox.Show("祝您中頭獎:D");
                    }
                }
            }
        }
    }
}

全系列文章列表


上一篇
看範例學C#-09 struct結構
下一篇
看範例學C#-11 共用Click事件
系列文
看範例學C#30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言