2015-07-20 57 views
0

我想知道如何讓用戶輸入,然後檢查輸入的某些屬性,並顯示除了最後一個輸出以逗號分隔的輸出。這是迄今爲止我所擁有的。我與要求用戶輸入掙扎,並在輸出端也擺脫逗號:如何問用戶輸入

using System; 
class TestClass 
{ 
static void Main(string[] args) 
{ 

int x = Convert.ToInt32(Console.ReadLine()); 
if (x < 0 || x > 25) 
    Console.WriteLine("sorry, that number is invalid"); 

else 
    while (x <= 30) 
    { 
    if(x <= 30) 
     Console.Write(string.Join(",", x)); 
     Console.Write(", "); 

     x = x + 1; 
    } 
} 
} 
+0

你想用輸入做什麼?提供您期望的輸入和輸出示例。 – Cyral

+3

[Console.ReadLine()](https://msdn.microsoft.com/en-us/library/system.console.readline(v = vs.110).aspx) –

+0

嘗試使用['Char.GetNumericValue(String (),'Int32)'](https://msdn.microsoft.com/en-us/library/cdb0at4t(v = vs.110).aspx)on'Console.ReadLine –

回答

0

更改環路

while (x <= 30) { 
    Console.Write(x); 
    if (x < 30) { // Execute for all except for x == 30 
     Console.Write(", "); 
    } 
    x++; 
} 

String.Join爲加入的項目數組。這不是你想要的。

您還可以使用StringBuilder。它允許刪除最後的", "

var sb = new StringBuilder(); 
while (x <= 30) { 
    sb.Append(x).Append(", "); 
    x++; 
} 
sb.Length -= 2; // Remove the 2 last characters ", " 
Console.WriteLine(sb); 
0

目前尚不清楚你正在努力完成什麼。也許這樣?

void Main() 
{ 
    int x; 
    List<int> numbers = new List<int>(); 

    while (true) 
    { 
    Console.WriteLine ("Enter a whole number between 1 and 25 or 0 to end:"); 
    string input = Console.ReadLine(); 

    bool isInteger = int.TryParse(input, out x); 

    if (!isInteger || x < 0 || x > 25) 
    { 
     Console.WriteLine (@"Didn't I tell you ""Enter a whole number between 1 and 25 or 0 to end? Try again"""); 
     continue; 
    } 

    if (x == 0) 
    { 
     if (numbers.Count() == 0) 
     { 
     Console.WriteLine ("Pity you quit the game too early."); 
     } 
     else 
     { 
     Console.WriteLine (@"You have entered {0} numbers. The numbers you entered were:[{1}] 
Their sum is:{2} 
and their average is:{3}", 
      numbers.Count, 
      string.Join(",", numbers.Select (n => n.ToString())), 
      numbers.Sum(), 
      numbers.Average()); 
     } 
     break; 
    } 
    else 
    { 
     numbers.Add(x); 
    } 
    } 
}