Answer to Question #199410 in C# for Nkhululeko Chabala

Question #199410

Write a user defined method named getMark that can be used to get a valid mark from the user. Your method must continuously ask the user for a mark, until a valid mark is entered (valid marks are between 0 and 100). If a user enters an invalid mark, display an error message before asking for a valid mark to be entered. The method must return the valid value to the calling program.


1
Expert's answer
2021-05-27T11:31:06-0400
using System;

namespace Test
{
    class MarkTest
    {
        static int getMark()
        {
            while(true)
            {
                Console.Write("Please enter the mark (mark range is [0; 100]): ");
                string   line  = Console.ReadLine();
                string[] words = line.Split();

                if(words.Length != 1)
                {
                    Console.WriteLine("Error: too many data\n");
                    continue;
                }

                int mark;
                if(!int.TryParse(words[0], out mark))
                {
                    Console.WriteLine("Error: can't parse entered data to integer\n");
                    continue;
                }

                if(mark < 0 || 100 < mark)
                {
                    Console.WriteLine("Error: the mark must be in the range [0; 100]\n");
                    continue;
                }

                return mark;
            }
        }

        static int Main()
        {
            Console.WriteLine("The mark entered by user is {0}", getMark());
            return 0;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS