如何初始化数组并随后对其进行操作 [英] How to initrialize arrays and manipulate them afterwards
问题描述
我想创建一个整数数组,然后初始化每个整数.
初始化必须由程序的用户完成.
之后,我想将数组的元素保存在文本文件中并在那里进行操作.
然后,必须将文本文件中的字符串保存到可以在控制台上打印的新数组中.
这是一个控制台应用程序
[edit]仅标记-OriginalGriff [/edit]
I want to create an array of integers and then initialize each of them.
The initialisation must be done by the user of the program.
fter that, I want to save the elements of the array in a textfile and manipulate them there.
The string in the textfile must then be saved in a new array which can be printed on the console.
This is a Console Application
[edit]Tags only - OriginalGriff[/edit]
推荐答案
好吧,这是您的功课,所以我不会为您提供完整的代码.不过,这里有一些指针:
1)获取用户要输入的数字.如果不知道,就不知道要分配多大的数组.
您将需要:Console.ReadLine,int.Parse或int.TryParse-Google在其末尾附加"MSDN".
2)分配数组.
Well, it''s your homework, so I''m not going to give you the full code. Here are some pointers though:
1) Get the number of numbers the user is going to enter. If you don''t know this, you don''t know how big an array to allocate.
You will need: Console.ReadLine, int.Parse or int.TryParse - Google for them appending "MSDN" on the end.
2) Allocate the array.
int[] myArray = new int[numberOfNumbersTheUSerWillEnter];
3)您将需要一个循环来获取数字.
3) You will need a loop to get the numbers.
for (int i = 0; i < numberOfNumbersTheUSerWillEnter; i++)
4)在循环中,按照与上述(1)相同的方式从用户读取一个数字,并将其填充到适当的数组元素中:
4) In the loop, read a number from the user as you did in (1) above, and stuff it into the appropriate array element:
myArray[i] = numberIJustGotFromTheUser;
5)然后使用第二个循环将数字写入文件.
6)然后从文件中读取数字,并将其打印到控制台.
如果您对此有任何特定的疑问,请随时提出.但是不要指望我们为您编写它-这是您的作业,而不是我们的作业!
5) Then use a second loop to write the numbers to a file.
6) Then read the numbers form the file, and print them to the console.
If you have a specific problem with any of this, feel free to ask. But don''t expect us to write it for you - it''s your homework, not ours!
尝试使用List类:
Try to use List class:
List<int> list = new List<int>();
list.Add(777);
您也可以尝试一下,
You can try this too,
Console.WriteLine("Please enter the number of Entries");
int noOfEntries = int.Parse(Console.ReadLine());
int[] numbers=new int[noOfEntries];
Console.WriteLine("Please Enter the numbers");
for(int i= 0;i<noofentries;i++){>
numbers[i] = int.Parse(Console.ReadLine());
}
for(int j=0;j<numbers.length;j++){>
File.AppendAllText("textfile.txt",numbers[j]+Environment.NewLine);
}
然后将其读回数组,
你可以做这样的事情
Then to read it back into an array,
You can do something like this
int[] readBack = File.ReadAllLines("filename.txt")
.Select(s=>int.Parse(s)).ToArray();
这篇关于如何初始化数组并随后对其进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!