Why the Int.parse ("AB") error occurs in C # for type conversion

Source: Internet
Author: User

First, the question

  

In the judgment of a simple leap year question, the input box gets the string, and we want to enter a string of numbers and convert the string to an int integer to judge. Write the program as follows

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.threading.tasks;using system.windows.forms;namespace windowsformsapplication2{public partial class Form1:form {public Form1 () {Initializeco        Mponent (); private void textBox1_TextChanged (object sender, EventArgs e) {} private Boolean checkleap (            int year) {bool temp = false;            if (year% 4 = = 0) {temp = true;            } if (year% = = 0) {temp = false;            } if (year% = = 0) {temp = true;        } return temp; } private void Form1_Load (object sender, EventArgs e) {} private void button1_click (object se NDEr, EventArgs e) {String str = Textbox1.texT            String str1 = ""; if (checkleap (int).            Parse (str))) {str1 = "Enter year for leap years";            } else {str1 = "The input result is not a leap year";        } MessageBox.Show (STR1); }    }}

But Int.parse ("AB") throws an exception when we enter illegal characters.

Why does Int.parse ("AB") throw an exception? What should be done?

Let's talk about several types of conversions in C # first

Two, several types of conversion mode.

 

1. (int) is a type conversion, when we can use implicit conversions from the int type to the Long,float,double,decimal type, but when we need to use an explicit conversion from the long type to the int type, a compilation error is generated

2.int. Parse () is a class-tolerant transformation that converts a string of numeric content into an int type.

Throws a ArgumentNullException exception if the string is empty;

Throws a FormatException exception if the string content is not a number;

Throws a OverflowException exception if the string content represents a number that is outside the range represented by the int type;

3, Int. TryParse and Int. Parse is more similar, but it does not produce an exception, the conversion succeeds and returns True, and the conversion fails to return false.

The last parameter is the output value, if the conversion fails, the output value is 0, if the conversion succeeds, the output value is the converted int value

4, Convert.ToInt32 () is a class-tolerant conversion, but it is not limited to converting a string to an int type, or another type of parameter;

Comparison: When the Convert.ToInt32 parameter is null, returns 0; Int. Throws an exception when the Parse parameter is null. Throws an exception when the Convert.ToInt32 parameter is ""; Int.   Throws an exception when the Parse parameter is "". Convert.ToInt32 can convert more types; int. Parse can only convert strings of numeric types

Three, the problem analysis

Because the input string AB is not a number, it runs out of "FormatException".

In the type conversion discussion, we mentioned Int. TryParse may solve the problem.

The revised key code is as follows:

  

1        Private voidButton1_Click (Objectsender, EventArgs e)2         {3String str =TextBox1.Text;4String str1 ="";5             intnum =0;6             BOOLtemp =int. TryParse (str, outnum);7             if(temp)8             {9                 if(Checkleap (num))TenSTR1 ="enter years as leap year"; One                 Else ASTR1 ="The input result is not a leap year"; -             } -             Else the             { -STR1 ="The input year is not properly formatted"; -             } - MessageBox.Show (str1); +}

Test Case:

Test Cases Expected output Actual output
"1234" The input result is not a leap year The input result is not a leap year
"2000" Enter the result as a leap year Enter the result as a leap year
"1900" The input result is not a leap year The input result is not a leap year
"ABCD" The input year is not properly formatted The input year is not properly formatted
“” The input year is not properly formatted The input year is not properly formatted

Test:

So in future programming, we should pay attention to int. The use of Tryparse (), and consideration of various situations.

Why the Int.parse ("AB") error occurs in C # for type conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.