C
C#2y ago
appi

❔ User inputs & arrays.

I am having the user input a max amount of values to store and using that input as my array length. I am then having the user input that amount of values individually. EX: User inputs 5, then inputs 1, 2, 3, 4, 5 I am trying to limit the amount of inputs to the max value inputted by the user. Everything I have tried so far allows the user to input more than the max amount they specified and I get Out of Range error. Anyone have a link to some documentation or some advice? I would prefer not to be outright told the answer.
14 Replies
Angius
Angius2y ago
Well, check what the user entered, and see if it's more than the array length?
if (userInput >= theArray.Length)
{
Console.WriteLine($"⚠ No can do, maximum is {theArray.Length}");
}
if (userInput >= theArray.Length)
{
Console.WriteLine($"⚠ No can do, maximum is {theArray.Length}");
}
JakenVeina
JakenVeina2y ago
define "limit the amount of inputs" like, prevent the user from typing in more than a certain amount of characters?
appi
appiOP2y ago
If the user inputs 5 as how many values they want to store, I want to make it so they can only enter 5 inputs
Angius
Angius2y ago
Use a list and keep checking the count
appi
appiOP2y ago
yeah, but the user will be pressing enter after every value
Angius
Angius2y ago
If count reaches or exceeds maximum, don't allow input
JakenVeina
JakenVeina2y ago
oh, okay you made it seem like they would be entering all the array values at once, comma-separated
appi
appiOP2y ago
oops, sorry about that
Angius
Angius2y ago
var elements = new List<string>();
while (elements.Count < maximum)
{
Console.WriteLine("Add new element");
elements.Add(Console.ReadLine());
}
var elements = new List<string>();
while (elements.Count < maximum)
{
Console.WriteLine("Add new element");
elements.Add(Console.ReadLine());
}
JakenVeina
JakenVeina2y ago
if control is swapping back and forth between the program and the user, after every input, then you have full control over just... not allowing control to go back to the user
appi
appiOP2y ago
okay, that makes sense. thank you. I will try that would a for loop with a nested do while loop work?
JakenVeina
JakenVeina2y ago
probably sounds like overkill
appi
appiOP2y ago
i figured it out thank you gents
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server