[英]C# user input int to array
我要用戶輸入5個數字並將其存儲到數組中,這樣我就可以在方法中發送值並從每個數組中減去5個數字。 當我使用:
for(I=0;I<5;I++) {
int[] val = Console.ReadLine();}
它說我不能將int []轉換為int。 我的編程有些生疏。 我也不知道如何將數組值從main發送到方法。
您正在將來自控制台的字符串輸入分配給一個int數組。 這是錯誤的,原因有兩個:
int
數組( int[]
)是ints
的集合。 int
,需要首先進行解析。 這是一個輕微的轉移,但是我也不認為您應該使用數組。 數組在C#中的功能通常比內置List<T>
少得多。 ( 這里有所有的搖滾明星。)有人說根本沒有理由使用數組-我不會走那么遠,但是我認為對於這種用例,僅將項目添加到List
比將其容易得多。分配5個空格並按索引初始化值。
無論哪種方式,都應該使用int.TryParse()
而不是int.Parse()
,因為如果不檢查用戶輸入是否可解析為int
則將立即獲得異常。 因此,用於從用戶獲取字符串的示例代碼如下所示:
List<int> userInts = new List<int>();
for (int i = 0; i < 5; i++)
{
string userValue = Console.ReadLine();
int userInt;
if (int.TryParse(userValue, out userInt))
{
userInts.Add(userInt);
}
}
如果您仍然想使用數組,或者必須使用,只需將List<int> userInts
...替換為int[] userInts = new int[5];
,然后將userInts.Add(userInt)
替換為userInts[i] = userInt;
。
您首先初始化數組
int[] val = new int[5];
然后在執行for循環時:
for (int i=0; i<val.Length; i++)
{
val[i] = int.Parse(Console.ReadLine());
}
提示:要將數組值從main發送到方法,只需查看static void main
是如何形成的:
static void Main(string[] args)
意思是main接受控制台參數的字符串數組。
您只需要首先將從控制台輸入的string
解析為int。您可以通過以下方式接受int:
for(int i=0;i<myArray.Length;i++) {
myArray[i] = int.Parse(Console.ReadLine()); //Int32.Parse(Console.ReadLine()) also works
就像@Furkle所說的那樣,最好總是使用TryParse()
來執行異常處理。 MSDN對此有一個很好的教程 。
furkle是正確的,因為console.ReadLine方法返回一個字符串,並且不能將字符串分配給int數組,所以它不起作用。 但是,提供的解決方案有點笨拙,因為它一次只能從控制台讀取一個字符。 最好一次接受所有輸入。
這是一個簡短的控制台程序,
包括錯誤處理。
static void Main(string[] args){
var intList = new List<int>();
string sUserInput = "";
var sList = new List<string>();
bool validInput = true;
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
try
{
foreach (var item in sList) {intList.Add(int.Parse(item));}
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
} while (validInput == false);
Console.WriteLine("\r\nHere are the contents of the intList:");
foreach (var item in intList)
{
Console.WriteLine(item);
}
Console.WriteLine("\r\npress any key to exit...");
Console.ReadKey();
}//end main
如果要確保用戶僅輸入5個整數,則可以執行DO WHILE循環,如下所示:
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
if (sList.Count > 5)
{
validInput = false;
Console.WriteLine("you entered too many integers. You must enter only 5 integers. \r\n");
}
else
{
try
{
foreach (var item in sList) { intList.Add(int.Parse(item)); }
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
}
} while (validInput == false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.