编程知识 cdmana.com

Java introduction lesson 94 -- parseInt method of integer

problem

     test Integer Of parseInt Method , namely , First, string "123" Convert to int Type and output results , then , The string " One hundred and twenty ginseng " Convert to int type , And see how it works .

programme

     First , Use Integer Of parseInt Method , The string "123" Convert to int type , Normal operation and output int Type value 123; then , Again using Integer Of parseInt Method , The string " One hundred and twenty ginseng " Convert to int type , After operation , There will be anomalies .

step

     To implement this case, follow the steps below .

Step one : Build test methods

     stay day02 New class under package TestInteger, Add test methods to this class testParseInt, The code is as follows :

    package day02;
    
    import org.junit.Test;
    
    public class TestInteger{
    /**
     * test Integer Of parseInt Method 
     */
     @Test
     public void testParseInt(){
     
     }
    }

Step two : The string "123" Convert to integer type

     Use Integer Of parseInt Method , The string "123" Convert to int type , Normal operation and output int Type value 123, The code is as follows :

    package day02;
    
    import org.junit.Test;
    
    public class TestInteger{
    /**
     * test Integer Of parseInt Method 
     */
     @Test
     public void testParseInt(){
     
         String str="123";
         int value=Integer.parseInt(str);
         System.out.println(value);//123
     }
    }

     Run the above code , The console output is :

    123

     It indicates that the string "123" Convert to int Type of 123.

Step three : character string " One hundred and twenty ginseng " Convert to int type

     Again using Integer Of parseInt Method , The string " One hundred and twenty ginseng " Convert to int type , The code is as follows :

    package day02;
    
    import org.junit.Test;
    
    public class TestInteger{
    /**
     * test Integer Of parseInt Method 
     */
     @Test
     public void testParseInt(){
     
         String str="123";
         int value=Integer.parseInt(str);
         System.out.println(value);//123
         
         str=" One hundred and twenty ginseng ";
         // Will throw out NumberFormatException
         value=Integer.parseInt(str);
     }
    }

     After running the above code , There will be anomalies :

java.lang.NumberFormatException:For input string:" One hundred and twenty ginseng "

     It can be seen from the abnormal situation that ,Java The program could not string " One hundred and twenty ginseng " Convert to int type , therefore , Throw out java.lang.NumberFormatException abnormal . So it's using Integer Of parseInt When the method is used , Note that the parameters of the passed in method are numbers .

Official account , Get a learning video

版权声明
本文为[Monkeys learn to program]所创,转载请带上原文链接,感谢

Scroll to Top