我正在上课,我们的任务是以下问题。我不确定我是在读这个问题还是根本不理解它。我知道如何获得随机数设置,但我仍然坚持如何允许用户指定保存到文件的数量。任何帮助都会很棒。
问题: 编写一个程序,将一系列随机数写入文件。 每个随机数应在1到100的范围内。 应用程序应该让用户指定文件将保留的随机数。
这是我到目前为止所拥有的。它的工作原理除了文本文件只保存生成的最后一个随机数而不是所有随机数。
'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;
using System.IO;
namespace Random_Number
{
public partial class Form1 : Form
{
// Variable
int result = 0;
public Form1()
{
InitializeComponent();
}
private void generateButton_Click(object sender, EventArgs e)
{
try
{
// Get how many random numbers the user wants
int myRandomNumbers = int.Parse(howManyTextBox.Text);
// Create the random object
Random rand = new Random();
for (int i = 0; i < myRandomNumbers; i++)
{
// Create the list of random numbers
result = rand.Next(1, 101);
// Display the random numbers in the ListBox
randomNumbersListBox.Items.Add(result);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void saveAs_Click(object sender, EventArgs e)
{
StreamWriter outputFile;
if (saveFile.ShowDialog() == DialogResult.OK)
{
// Create the selected file
outputFile = File.CreateText(saveFile.FileName);
// Write data to the file
outputFile.WriteLine(result);
// Close the file
outputFile.Close();
}
else
{
MessageBox.Show("Operation Cancelled");
}
}
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the ListBox and TextBox
howManyTextBox.Text = "";
randomNumbersListBox.Items.Clear();
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the program
this.Close();
}
}
}'
答案 0 :(得分:1)
class Program
{
static void Main(string[] args)
{
Console.Write("Enter count: ");
var count = int.Parse(Console.ReadLine());
Console.Write("Writing numbers... ");
WriteNumbers(count);
Console.WriteLine("Done.");
}
static void WriteNumbers(int count)
{
var gen = new Random();
var file = new StreamWriter("YourFile.txt", false);
for (var i = 0; i < count; i++)
{
file.Write(gen.Next(1, 100) + " ");
}
file.Close();
}
}