views:

508

answers:

5
+1  Q: 

switch statement

Hi I'm practicing the "Switch Loop" in a program. And I'm making a code where a user can input the integer and after the user will input the integer it will also display what the user just typed in. Now I'm trying to implement where the program will ask the user to input the number again by selecting the Y/N. I already included it here in my code but if I type characters the first time the program asks me to type an integer, the program will execute the catch part. How can I make it that if the user will type a character it will also display the message again, "please enter the integer:"

Thanks for your help I'm quite lost in somewhere here.

          int enterYourNumber;
          char shortLetter;

            try
            {
                Console.WriteLine("Please enter the integer: ");
                enterYourNumber = Convert.ToInt32(Console.ReadLine());
                WriteNumber(enterYourNumber);

                Console.WriteLine("Do you still want to enter a number? Y/N");
                shortLetter = Convert.ToChar(Console.ReadLine());

                while (shortLetter == 'y' || shortLetter == 'Y')
                {
                    Console.WriteLine("Please enter the integer: ");
                    enterYourNumber = Convert.ToInt32(Console.ReadLine());
                    WriteNumber(enterYourNumber);

                    Console.WriteLine("Do you still want to enter a number? Y/N");
                    shortLetter = Convert.ToChar(Console.ReadLine());
                }

            }
            catch
            {                                        
                Console.WriteLine("Please enter an integer not a character");
            }
        }

            public static void WriteNumber(int wordValue)
            {

            switch (wordValue)
            {
                case 1:
                    Console.WriteLine("You have entered number one");
                    break;
                case 2:
                    Console.WriteLine("You have entered number two");
                    break;
                case 3:
                    Console.WriteLine("You have entered number three");
                    break;
                default:
                    Console.WriteLine("You have exceeded the range of number 1-3 ");
                    break;
            }

======================

This is what I did I don't know why I'm getting an error. The new method seems not to work:

        int enterYourNumber;
        char shortLetter;


          do
        {
            enterYourNumber = GetNumber();
            WriteNumber(enterYourNumber);                
            Console.WriteLine("Do you still want to enter a number? Y/N");
            shortLetter = Convert.ToChar(Console.ReadLine());
         }
       while (shortLetter == 'y' || shortLetter == 'Y')
        {
            Console.WriteLine("Please enter the integer: ");
            enterYourNumber = Convert.ToInt32(Console.ReadLine());
            WriteNumber(enterYourNumber);

            Console.WriteLine("Do you still want to enter a number? Y/N");
            shortLetter = Convert.ToChar(Console.ReadLine());
        }
    }



       public static int GetNumber() 
       {
       bool done = false;
       int value;
       while ( !done ) 
        {
            Console.WriteLine("Please enter the integer: ");
        try 
        {
            value = Convert.ToInt32(Console.ReadLine());
            done = true;
        }
       catch 
        {
            Console.WriteLine("Please enter an integer not a character");
        }
        }
       }

=============

Hi Bill this is the example you gave and it seems I'm still getting an error: could you please the code. Thank you very much:

    public static void Main(string[] args)
    {
        int enterYourNumber;
        char shortLetter;



        do
        {
            enteryourNumber = GetNumber();
            WriteNumber(enteryourNumber);
            Console.WriteLine("Do you still want to enter a number? Y/N");
            shortLetter = Convert.ToChar(Console.ReadLine());
        } 
        while (shortLetter == 'y' || shortLetter == 'Y');
    }


    public static int GetNumber()
    {
        bool done = false;
        int value;
        while (!done)
        {
            Console.WriteLine("Please enter the integer: ");
            try
            {
                value = Convert.ToInt32(Console.ReadLine());
                done = true;
            }
            catch
            {
                Console.WriteLine("Please enter an integer not a character");
            }

            Console.WriteLine("Please enter the integer: ");
            enterYourNumber = Convert.ToInt32(Console.ReadLine());
            WriteNumber(enterYourNumber);
            Console.WriteLine("Do you still want to enter a number? Y/N");
            shortLetter = Convert.ToChar(Console.ReadLine());   
        }
    }

    public static void WriteNumber(int wordValue)
    {

        switch (wordValue)
        {
            case 1:
                Console.WriteLine("You have entered number one");
                break;

            case 2:
                Console.WriteLine("You have entered number two");
                break;

            case 3:
                Console.WriteLine("You have entered number three");
                break;

            default:
                Console.WriteLine("You have exceeded the range of number 1-3 ");
                break;
        }
    }
}

}

=================

Hi again this question is for Robert. This is what I did now, but if I enter "N" it will not exit the program. It still asked the same question. Any idea: Thanks:

    public static void Main(string[] args)
    {
        int enterYourNumber;
        char shortLetter;
        bool validEntry;



        while (true)
        {
            do
            {
                Console.WriteLine("Please enter an integer: ");
                string numberString = Console.ReadLine();
                validEntry = int.TryParse(numberString, out enterYourNumber);
                WriteNumber(enterYourNumber);
                if (!validEntry)
                {
                    Console.WriteLine("Entry must be an integer");
                }
            } while (!validEntry);

            Console.WriteLine("Do you still want to enter a number? Y/N");
            shortLetter = Convert.ToChar(Console.ReadLine());


        }
     }




    public static void WriteNumber(int wordValue)
    {
        switch (wordValue)
        {
            case 1:
                Console.WriteLine("You have entered number one");
                break;
            case 2:
                Console.WriteLine("You have entered numbered two");
                break;
            case 3:
                Console.WriteLine("You have entered numbered three");
                break;
            default:
                Console.WriteLine("You have exceeded the range of number 1-3");
                break;
        }
    }
}

}

====================================

Hi Robert and Bill here is what I got now. Would appreciate if you could give some ideas on how to improve the coding. Thanks for your help.

     public static void Main(string[] args)
     {
        int intEnterYourNumber;
        char charShortLetter;
        string strUserInput;

        do
        {
            do
            {
                Console.WriteLine("Please enter the integer: ");
                strUserInput = Console.ReadLine();
            } while (!int.TryParse(strUserInput, out intEnterYourNumber));
            WriteNumber(intEnterYourNumber);
            Console.WriteLine("Do you still want to enter a number? Y/N");
            charShortLetter = Convert.ToChar(Console.ReadLine().ToUpper());
        } while (charShortLetter == 'Y');
    }



    public static void WriteNumber(int wordValue)
    {
        switch (wordValue)
        {
            case 1:
                Console.WriteLine("You have entered number one");
                break;
            case 2:
                Console.WriteLine("You have entered numbered two");
                break;
            case 3:
                Console.WriteLine("You have entered numbered three");
                break;
            default:
                Console.WriteLine("You have exceeded the range of number 1-3");
                break;
        }
    }
+2  A: 
do
{
    Console.WriteLine("Please enter the integer: ");                
    enterYourNumber = Convert.ToInt32(Console.ReadLine());                
    WriteNumber(enterYourNumber);                
    Console.WriteLine("Do you still want to enter a number? Y/N");                    
    shortLetter = Convert.ToChar(Console.ReadLine());
}                
while (shortLetter == 'y' || shortLetter == 'Y')
Robert Harvey
thanks Robert how about if the user will input a character for the first time?
tintincute
Put this Do/While in your try/catch, as in the original code.
Robert Harvey
Unfortunately, it doesn't let the user back into the loop after an exception, which was the question put.
Bill James
Hi Bill I tried what you suggested but it seems that I'm still getting an error. I would be happy if you could check the code. Thanks
tintincute
+1  A: 

Robert's is a start, but perhaps we still want to try catch...

Replace your main function with:

do
{
    enterYourNumber = GetNumber();
    WriteNumber(enterYourNumber);                
    Console.WriteLine("Do you still want to enter a number? Y/N");
    shortLetter = Convert.ToChar(Console.ReadLine());
}
while (shortLetter == 'y' || shortLetter == 'Y')

and add this function:

public static int GetNumber() {
    boolean done = false;
    int value;
    while ( !done ) {
        Console.WriteLine("Please enter the integer: ");
        try {
            value = Convert.ToInt32(Console.ReadLine());
            done = true;
        }
        catch {
            Console.WriteLine("Please enter an integer not a character");
        }
    }
}

Then remove your try catch in the main function.

Bill James
Hi Bill please see my edited answer it seems the new method is having a problem here
tintincute
Well, you have extra code after the "while" line. That while line is the last statement of the initial block (before the function declarations)
Bill James
Hi Bill I tried what you suggested but it seems that I'm still getting an error. I would be happy if you could check the code. Thanks
tintincute
+1  A: 

Since you are learning, you might also consider handling the error differently.
Have a look at the SO question: In C# should try-catch be used for is-numeric testing? for more ideas and discussion.

Doug L.
thank you Doug I'll take note of that.
tintincute
A: 

Move the try/catch block inside the loop. Robert Harvey's suggestion of the do/while loop is good, too.

 int enterYourNumber;
 char shortLetter;

 do
 {
      try
      {
          Console.WriteLine("Please enter the integer: ");                
          enterYourNumber = Convert.ToInt32(Console.ReadLine());                
          WriteNumber(enterYourNumber); 
      }
      catch( FormatException )
      {                                        
          Console.WriteLine("Please enter an integer not a character");
      }  

      shortLetter = '\0';
      do
      {
          try
          {
              Console.WriteLine("Do you still want to enter a number? Y/N");                    
              shortLetter = Convert.ToChar(Console.ReadLine());
          }
          catch( FormatException ) 
         {
              Console.WriteLine("Please enter a single character");
         }
      }     
      while ( shortLetter == '\0' )      
 }                
 while (shortLetter == 'y' || shortLetter == 'Y')

 }

        public static void WriteNumber(int wordValue)
        {

        switch (wordValue)
        {
            case 1:
                Console.WriteLine("You have entered number one");
                break;
            case 2:
                Console.WriteLine("You have entered number two");
                break;
            case 3:
                Console.WriteLine("You have entered number three");
                break;
            default:
                Console.WriteLine("You have exceeded the range of number 1-3 ");
                break;
        }
UncleO
thank you uncleo this one works pretty well. I'm still not with the "Do-WHiLe" Statement so I have to review this again and understand the logic. Because in my previous code, it seems that it's quite redundant and I think this is what I need.
tintincute
The key to the Do While statement is that, in programs that require user input, putting the While at the bottom ensures that the loop executes at least once, and that the user gets to input at least once. You won't always write your While loops this way. Most of the time you will only want to enter the loop if the While condition is satisfied.
Robert Harvey
uncleo I tried again your work the first "shortletter==null"can't be executed because Null can't be converted in char. And the second catch(FormatException) doesn't work as well.
tintincute
hi again uncleo, I found out that the FormatException is wrong spelling. I fixed it but then with the "shortletter ==null" i'm still getting an error here. I don't know what's wrong with the code.
tintincute
Silly me. I was treating a char as an object. It's a primitive type. Still, this is a common pattern: Set a variable to a "sentinel" value, then test for the sentinel. But note that I wrote this answer because you wanted to use try/catch blocks. You would be better to follow to the others' advice in this case and use TryParse() instead.
UncleO
No problem uncleo. I tried it and it worked fine. I also tried without the try/catch. I think without try/catch is better. But at least I tried.thanks again;-)I also posted new version without try/catch.
tintincute
+8  A: 

I think your code would be easier to learn and understand if you did not use exceptions to test your numbers. Try using int.TryParse() instead (TryParse() on MSDN). TryParse() returns true (or false) depending on whether the entered number was valid:

int number;
bool validEntry = int.TryParse(enterYourNumber, out number);
if (!validEntry)
{
    Console.WriteLine("Entry must be an integer.");
}

Also, learn about the do...while loop (link). a do..while loop is similar to a regular while loop except a do-while loop is executed once before the conditional expression is evaluated.

bool validEntry;
int enteredNumber;
do
{
    Console.Write("Please enter the integer: ");
    string numberString = Console.ReadLine();
    validEntry = int.TryParse(numberString, out enteredNumber);
    if (!validEntry)
    {
        Console.WriteLine("Entry must be an integer.");
    }
} while (!validEntry);

Wrap the whole thing in another while loop ("Do you still want to enter a number (Y/N)?") and you're done.

Enjoy,

Robert C. Cartaino

Robert Cartaino
Thanks for the link Robert, will try your example and will learn the do while loop. That means, the "try and catch" in C# is not good for beginners like me?
tintincute
You should only ever use try...catch in exceptional (excuse the pun) circumstances. It should never be used for normal (expected) program flow.
rein
Hi Robert I have a question please checked my edited notes above. thanks. The "N" here doesn't work if I want to exit my program.I'm not sure If I wrote the another while correctly. please see my code. thanks.
tintincute
First, create another do..while loop (just like the first one) to check for a valid "(Y/N)" answer. Use Console.ReadKey() to get your answer (it's easier). Then, regarding your outer-most "while(true)" loop... it will never end. You can change it to a do..while loop and and use the answer to your "(Y/N)" question to test whether to leave your outer-most loop.
Robert Cartaino
Tintin, you're not checking the value of the entered character in the Y/N question... you're just reading it. Something like "if (shortLetter != 'Y') break;" will get you out of the loop if you don't type Y.
Bill James
@Robert: I see, thanks for additional input. I'll put my result later on. Thanks again
tintincute
@Bill: THanks for the input I'll try that and will post the result later on;-) have a good day:-)
tintincute