我正在处理一个应用程序,该应用程序让用户选择要输入数组的整数,然后让他们输入要添加到数组中的数字。输入每个数字后,它会显示用户在垂直列表中输入的所有非重复整数。如果它不是唯一的,它会通知用户它已被输入。
我不确定如何在每个输入的整数中创建应用程序列表,而不仅仅是最新的整数。
这是我的代码:
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
int[] array = new int[manyNumbers];
//starts asking for numbers
for (int i = 0; i < manyNumbers;)
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
array[i++] = val;
}
//checks to see if already entered
else if (i > 0 && array.Take(i).Contains(val))
{
Console.Write("{0} has already been entered", val);
array[i++] = val;
}
//prints inputted integer
else {
array[i++] = val;
Console.WriteLine("{0}", val);
}
}
}
答案 0 :(得分:1)
到目前为止,只需循环遍历数组。
原谅我的移动设计代码,但或多或少这样:
//prints inputted integer
else {
array[i++] = val;
for(int j=0 ; j<i;j++) {
Console.WriteLine("{0}", array[j]);
}
}
答案 1 :(得分:0)
非常基本的方法,请尝试以下方法之一:
for(var x=0;x<array.length;x++)
或
foreach(var i in array)
但是您的用例,请使用HashSet data structure
数学上,Set是唯一的事物列表。
答案 2 :(得分:0)
您可以使用foreach
循环
foreach(int num in array)
{
Console.WriteLine("{0}", num);
}
答案 3 :(得分:-1)
尝试此代码,它使用字典将列表保留在内存中并搜索以查看是否已添加整数,
using System.Collections.Generic;
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
Dictionary<int, int> array = new Dictionary<int, int>();
//starts asking for numbers
for (int i = 0; i < manyNumbers; )
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
}
//checks to see if already entered
else
if (i > 0 && array.ContainsKey(val))
{
Console.Write("{0} has already been entered", val);
//array[i++] = val;
}
else
{
//* add the new integer to list
array.Add(val, 0);
//prints the complete list
List<int> keys = new List<int>(array.Keys);
Console.WriteLine();
for(int j=0; j<keys.Count; j++) Console.WriteLine(keys[j]);
}
}
}