C
C#15mo ago
apparition

❔ 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
Angius15mo 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
JakenVeina15mo ago
define "limit the amount of inputs" like, prevent the user from typing in more than a certain amount of characters?
apparition
apparition15mo 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
Angius15mo ago
Use a list and keep checking the count
apparition
apparition15mo ago
yeah, but the user will be pressing enter after every value
Angius
Angius15mo ago
If count reaches or exceeds maximum, don't allow input
JakenVeina
JakenVeina15mo ago
oh, okay you made it seem like they would be entering all the array values at once, comma-separated
apparition
apparition15mo ago
oops, sorry about that
Angius
Angius15mo 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
JakenVeina15mo 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
apparition
apparition15mo ago
okay, that makes sense. thank you. I will try that would a for loop with a nested do while loop work?
JakenVeina
JakenVeina15mo ago
probably sounds like overkill
apparition
apparition15mo ago
i figured it out thank you gents
Accord
Accord15mo 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
More Posts