如何仅使用if..else作为正整数 [英] How to use if..else for positive integers only

查看:101
本文介绍了如何仅使用if..else作为正整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用if..else语句只接受正整数而不需要catch(formatException)



我尝试过:



I want to use the if..else statement to only accept positive integers without needing catch(formatException)

What I have tried:

//ExceptionHandling.cs
//write a program not catching every exception
using System;

class ExceptionHandling
{
    static void Main(string[] args)
    {
      
        bool continueLoop = true;
        
        do
        {
            try
            {
                Console.WriteLine("Enter the first integer to add:");
                int a = Int32.Parse(Console.ReadLine());
                Console.WriteLine("Enter second integer to add:");
                int b = Int32.Parse(Console.ReadLine());
                int sum = a + b;

               if(a < 0)
                {
                    Console.WriteLine("Please enter a non-negative integer:", a);
                    Console.ReadLine();
                } 
                if (b < 0)
                {
                    Console.WriteLine("\nPlease enter a non-negative integer:", b);
                    Console.ReadLine();

                }
                      
               
                
                    
                    Console.WriteLine("\nTotal is {0}", sum);
                continueLoop = false;

            }//end try

            catch (FormatException formatException)
            {
                Console.WriteLine("\n" + formatException.Message);
                Console.WriteLine("Please enter an integer and try again. \n");

            }//end catch
        }
        while (continueLoop);   //end do-while


        Console.WriteLine("\nPress enter to exit.");
        Console.ReadLine();
    }
}

推荐答案

public int GetValue(string prompt)
   {
   int value;
   while (true)
      {
      Console.WriteLine(prompt);
      if (int.TryParse(Console.ReadLine, out value))
         {
         break;
         }
      }
   return value;
   }


试试这个:
using System;

public class Program
{
	public static void Main()
	{
		int input;
		bool isInteger = false;
		do
		{
			Console.WriteLine("Input a positive integer:");
			isInteger = Int32.TryParse(Console.ReadLine(), out input);
		}
		while (!(isInteger && input >= 0));
		Console.WriteLine("You have input " + input);
	}
}


这篇关于如何仅使用if..else作为正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆