2014-10-19 2 views
0

У меня возникли проблемы с проверкой, является ли пользовательский ввод целым/действительным числом и находится в диапазоне 12-36. Кажется, я не могу заставить программу выводить сообщение об ошибке, если вход не является числом. Мне нужна программа, чтобы проверить, является ли ввод числом с помощью Tryparse, но если это не сообщение об ошибке. Сообщение об ошибке не работает, вместо этого программа вылетает, когда я пытаюсь запустить ее.Обеспечение ввода пользователем не является строкой

Console.Write("Please enter the diameter of your pizza: "); // get user to input pizzaDiameter 

     Double.TryParse(Console.ReadLine(), out pizzaDiameter); // read the users keyboard 
     //and convert input to real number to hold as the pizzaDiameter variable 


     /********************************************************************************** 
      *                    * 
      *       PROCESSING           * 
      *                    * 
      * *******************************************************************************/ 

     while (pizzaDiameter != QUIT_PROGRAM && needInput) // Begin while loop 
     { 



      // determine if diameter is within 12 to 36 
      // if does not meet requirements show error message and have user enter in new diameter 
      //if (Double.TryParse(Console.ReadLine(), out pizzaDiameter)) 
      //{ 
       //Console.WriteLine("\nENTRY ERROR\n\nPizza diameter must be a whole or real number.\n\nPlease try again"); 
      //} 
      //else 
      //{ 
       //needInput = false; 
      //} 
       if (pizzaDiameter < MINIMUM_DIAMETER || pizzaDiameter > MAXIMUM_DIAMETER) 
       { 
        //error message detailing why the program failed to calculate 
        Console.WriteLine("\nENTRY RANGE ERROR\n\nPizza must have a diameter in the range of 12” to 36” inclusive!\n\nPlease try again"); 
       } 
       else 
       { //program is satisfied with the inputted amount and will now move on to the range checking 
        needInput = false; 



        //Determines the number of slices based on user inputted diameter 
        if (pizzaDiameter <= DIAMETER_SMALL)//checks if pizzaDiameter is <=small 
        { 
         pizzaSlices = (SLICES_MINIMUM);//sets pizzaSlices to the minimum of 8 
        } 
        else if (pizzaDiameter <= DIAMETER_MEDIUM)//diameter range for <24 
        { 
         pizzaSlices = (SLICES_MEDIUM);// sets number of slices to 12 
        } 
        else if (pizzaDiameter <= DIAMETER_LARGE)//diameter range for <30 
        { 
         pizzaSlices = (SLICES_HIGH);// sets number of slices to 16 
        } 
        else 
        { 
         pizzaSlices = (SLICES_MAXIMUM);//sets maximum slices because diameter is >30 
        } 
+3

', если (Double.TryParse (Console.ReadLine(), из pizzaDiameter)) {Console.WriteLine (" ок «); } else {Console.WriteLine («ошибка!»); } ' – Mephy

+3

Если программа« сбой », это означает, что исключение выбрасывается и не обрабатывается. Перехватите исключения, чтобы вы могли их изучить и обработать. – David

+1

Какое исключение бросается? –

ответ

0

В вашем коде есть логические ошибки и тривиальные ошибки.

Старт с движущимися первые две строки внутри цикла в то время, и удалить переменную needInput

// Just to enter the loop the first time.... 
double pizzaDiameter = 1.0d; 
const double QUIT_PROGRAM = 0.0d; 

while (pizzaDiameter != QUIT_PROGRAM) 
{ 
    Console.Write("Please enter the diameter of your pizza: (0 to exit) "); 

    // Add the NOT operator in front of the TryParse call 
    if(!Double.TryParse(Console.ReadLine(), out pizzaDiameter)) 
    { 
     ... false returned by TryParse 
     ... error message.... 
    } 
    else if(.... check for diameter min/max .....) 
    { 
     ... diameter not valid error message 
    } 
    else 
    { 
     .... start calculus.... 
    } 
    // end while here... 
    // if input is incorrect the loop restart until diameter = 0 
    // So, no need to ask again the pizza diameter in this point 
} 
Смежные вопросы