Reputation: 673
I want to add multiple values into an array, but I want to stop when I feel like it.
Here is the condition I added
while (numbers[i] != 10)
{
i++;
numbers[i] = int.Parse(Console.ReadLine());
Console.WriteLine(numbers[i]);
}
It will stop when the value entered is 10. But I want it to stop when I just press ENTER.
How do I do this?
Upvotes: 0
Views: 2408
Reputation: 67898
Declare numbers
like this.
List<int> numbers = new List<int>();
Then modify the loop as such.
while (numbers[i] != 10)
{
i++;
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) { break; }
numbers.Add(int.Parse(input));
Console.WriteLine(numbers[i]);
}
Upvotes: 0
Reputation: 437326
If you are asking about how to detect the "just press ENTER" condition:
var input = Console.ReadLine();
if (input == "") {
break;
}
numbers[i] = int.Parse(input);
// etc
Upvotes: 4
Reputation: 4253
I guess you are looking for some way to re-size the array, you can use Array.Resize
Upvotes: 0
Reputation: 1062502
var numbers = new List<int>();
string s;
while(!string.IsNullOrEmpty(s = Console.ReadLine())) {
numbers.Add(int.Parse(s));
}
Upvotes: 3