2015-07-20 58 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); 
    } 
    } 
}