2013-10-20 72 views
0

嗯,我試圖做一個簡單的程序,利用for循環並將用戶輸入添加到一次一個數組,這使用此如何循環通過用戶輸入c#創建的數組#

string []str = new string[10]; 
for (int i = 0; i < str.Length; i++) 
{ 
    Console.WriteLine("Please enter a number: "); 
    str[i] = Console.ReadLine(); 
} 

但是,當我嘗試通過數組與foreach語句循環,我得到一個錯誤,指出我不能隱式轉換字符串[]以鍵入字符串; foreach語句是這樣的:

int even=0; int odd=0; 

int[] Arr=new string [] {str}; 

foreach (int i in Arr) 
{ 
    if (i % 2 == 0) 
    { 
     even++; 
    } 
    else 
    { 
     odd++; 
    } 
} 

這裏是完整的源代碼,

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string[] str = new string[10]; 
      for (int i = 0; i < str.Length; i++) 
      { 
       Console.WriteLine("Please enter a number: "); 
       str[i] = Console.ReadLine(); 
      } 
      int even = 0; int odd = 0; 
      int[] Arr = new string[] { str }; 
      foreach (int i in Arr) 
      { 
       if (i % 2 == 0) 
       { 
        even++; 
       } 
       else 
       { 
        odd++; 
       } 
      } 
      Console.WriteLine("There is " + even + " even numbers."); 
      Console.WriteLine("There is " + odd + " odd numbers"); 
      Console.ReadLine(); 
      Console.ReadLine(); 
     } 
    } 
} 
+0

因爲你創建一個整數數組,並嘗試填充/使用字符串初始化。在第二個代碼框中檢查第二行代碼 –

回答

2

直接在整數,而不是字符串數組改變你的輸入代碼來保存用戶輸入

int i = 0; 
    int[]values = new int[10]; 
    while(i < values.Length) 
    { 
     Console.WriteLine("Please enter a number: "); 
     int result; 
     string input = Console.ReadLine(); 
     if(Int32.TryParse(input, out result) 
     { 
      values[i] = result; 
      i++; 
     } 
     else 
     { 
      Console.WriteLine("Not a valid integer"); 
     } 
    } 

這將避免錯誤,當在這一行int[] Arr=new string [] {str};你嘗試從一個字符串數組初始化一個整數數組,並且編譯器是不滿意的話

除了明顯的編譯錯誤,使用Int32.TryParse允許立即檢查如果用戶鍵入的東西是不是一個整數,你可以拒絕輸入

+0

小挑剔:str本身是一個字符串[]。所以,他實際上試圖添加一個字符串[]作爲元素到一個字符串[] ... Spinning heads ... :) – elgonzo

+0

哇,謝謝你的回答 –

+0

好,但你接受另一個,所以這不是非常適合你 – Steve

0

在該線下方您要創建來自您所有輸入的整數數組。但實際上這種語法是不正確的。首先,你正試圖從字符串數組中創建一個int數組。這不可能。其次,創建一個字符串數組,如 new string[]{"str", "str"},但您正在執行new string[]{str[]}。因此,要解決所有這些問題,我建議更換

int[] Arr=new string [] {str}; 

int[] Arr = str.Select(s => int.Parse(s)).ToArray(); 
+0

非常感謝你完美的工作 –