On request, this week a program was made to determine whether a year was a leap years. The logic is simple, and there's no code here. However, a problem was found in the process of writing this procedure.
When you enter a year, if you enter 1) the letter 2) empty 3) exceeds the upper bound of int, it throws exception.
The problem occurs when the string goes to int type.
First, there are two main ways to convert a string to int in Java
1.integer.parseint (s)
2.integer.valueof (s). Intvalue ();
These two methods are slightly different, and then we will analyze them.
First I use the first method, when the test data is the normal year, there is no problem, but when you test the abnormal data will throw exception:
Mainly for NumberFormatException:
1) When you enter a letter, that is, when the content is not a number, such as ABCD
2) When you enter as empty
3) When you enter an int beyond the limit
Then I used the second method and got the same result as the first.
How to solve this problem, so that users can enter content normally
The first thing I think about is the use of Try-catch
Is that the program can capture the exception and handle it accordingly.
The above code is when the input data can not be converted to int type, please enter the correct year prompt
TIPS:
1.integer.parseint (s) and integer.valueof (s). Intvalue () What is the difference between the test and the feeling is not much different, but integer.valueof (s) is very different from integer.parseint (s), mainly because the return value is different.
Integer.parseint (s) return value int type
Integer.valueof (s) returns a value of integer, the difference being that the latter is able to use some methods of integer.
2. In software testing can not only use normal data to test, because for the software practitioners, a lot of ideas deep-rooted, and the general user does not have these concepts, if you do not consider these users, then your program will have a lot of problems, like this leap year program
3.try-catch in use is really very useful, a program execution in many cases will be out of exception, and this method can help us to deal with the corresponding.
Methods of string-to-int in Java and error handling