how can I let user enter value not null, and if enter null repeat again until enter valid value

Osama Boshi 1 Reputation point
2021-09-26T04:08:57.533+00:00

how can I let user enter value not null, and if enter null repeat again until enter valid value using simple (bool , if , for , do while) I don't want use (try, Catch) or (TryParse )

Console.Write("Enter required count marks: ");
int count = Convert.ToInt32(Console.ReadLine());
double[] mark = new double[count];

for (int i = 0; i < count; i++) 
{ 
    Console.Write("enter mark{0}: ", i + 1); 
    mark[i] = Convert.ToDouble(Console.ReadLine()); 
}
Developer technologies | C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2021-09-26T04:18:41.153+00:00

    You could add a nested loop and only break out when double.TryParse has parsed the input into the array element:

    Console.Write("Enter required count marks: ");
    int count = Convert.ToInt32(Console.ReadLine());
    double[] mark = new double[count];
    for (int i = 0; i < count; i++) {
        while (true) {
            Console.Write("enter mark{0}: ", i + 1);
    
            if (double.TryParse(Console.ReadLine(), out mark[i])) {
                break;
            }
        }
    }
    
    1 person found this answer helpful.

  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-09-26T10:49:10.147+00:00

    Unless the is a good reason to avoid using TryParse, I agree with @P a u l

    Here is an alternate for working with int values only.

    The following language extension keep code clean although you can take the code in the extension body and use directly in a loop.

    135287-figure1.png

    internal static class StringExtensions  
    {  
        public static bool IsInteger(this string sender)   
            => !string.IsNullOrEmpty(sender) && sender.All(char.IsDigit);  
    }  
    

    Test the extension

    while (true)  
    {  
          
        Console.Write("Enter value ");  
          
        string userInput = Console.ReadLine();  
      
        if (userInput.IsInteger())  
        {  
            Console.ForegroundColor = ConsoleColor.Yellow;  
            Console.WriteLine(Convert.ToInt32(userInput));  
        }  
        else  
        {  
            Console.ForegroundColor = ConsoleColor.Red;  
            Console.WriteLine($"'{userInput}' is not valid");  
        }  
      
        Console.ResetColor();  
      
        ConsoleKeyInfo ch;  
        Console.Write("Press the Escape (Esc) key to quit");  
        ch = Console.ReadKey();  
        if (ch.Key == ConsoleKey.Escape)  
        {  
            Environment.Exit(0);  
        }  
        Console.Clear();  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.