zoukankan      html  css  js  c++  java
  • 将String类型转换为int整数类型

    示例如下:

     1 public class demo {
     2 
     3     public static void main(String[] args) {
     4         
     5         String s="10";
     6         
     7         //String是字符串数据类型;s是变量;10是字符串
     8         
     9           int a =Integer.parseInt(s);
    10         
    11         /*因两者类型不匹配,不能从 String型 转换为 int型;
    12          * 
    13          * 则需要使用封装类,将String字符类型数据转换为Integer整型数据;
    14          */
    15         
    16         System.out.println("变量a的结果是"+a);
    17         
    18         //使用“+”进行字符串和变量a的拼接;
    19         
    20         s ="20";
    21         
    22         //变量s重新赋值;
    23                 
    24         System.out.println("重新赋值后变量a的结果是:"+s);
    25         
    26 
    27     }
    28 
    29 }

    输出结果为

    1 变量a的结果是10
    2 重新赋值后变量a的结果是:20

     假如:

    1 String s = " "
    2 //" "字符串是空的或者是"a""b"....

    示例如下:

     1 public class demo {
     2 
     3     public static void main(String[] args) {
     4         
     5         String s = " ";
     6         
     7         int a = Integer.parseInt(s);
     8         
     9         System.out.println(a);
    10         
    11         
    12     }
    13 
    14 }

    输出结果:会出现异常

    1 Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
    2     at java.lang.NumberFormatException.forInputString(Unknown Source)
    3     at java.lang.Integer.parseInt(Unknown Source)
    4     at java.lang.Integer.parseInt(Unknown Source)
    5 at demo03.main(demo.java:7)

    编译可以通过,因为"s"有值,而运行时会出现数字转换异常," "空的字符串不能转换为int整数数据类型。

     

  • 相关阅读:
    脚手架自建从开始到发布
    零散点总结
    2019.3.7 chrome72下载图片卡死问题
    2019.2.18 一九年的新篇章
    2018.10.12 布局终结
    2018.7.23 放大缩小菜单
    2018.7.19 横向收缩菜单动画
    2018.6.8 openlayers.js学习(汇总)
    Elasticsearch 排序
    easyui tree树节点上移下移 选中节点加背景色
  • 原文地址:https://www.cnblogs.com/japtx/p/11725279.html
Copyright © 2011-2022 走看看