5 回答

TA贡献1934条经验 获得超2个赞
在 Java 中要将 String 类型转化为 int 类型时,需要使用 Integer 类中的 parseInt() 方法或者 valueOf() 方法进行转换.
例1:
1 2 3 4 5 6 | String str = "123"; try { int a = Integer.parseInt(str); } catch (NumberFormatException e) { e.printStackTrace(); } |
例2:
1 2 3 4 5 6 | String str = "123"; try { int b = Integer.valueOf(str).intValue() } catch (NumberFormatException e) { e.printStackTrace(); } |
在转换过程中需要注意,因为字符串中可能会出现非数字的情况,所以在转换的时候需要捕捉处理异常

TA贡献1789条经验 获得超8个赞
String str = request.getParameter("s_id").trim(); //获取用户输入的学号的值
int s_id = Integer.parseInt(str); //把获取到的String类型的学号转化为int类型

TA贡献1725条经验 获得超7个赞
头文件:#include <stdlib.h>
atoi() 函数用来将字符串转换成整数(int),其原型为:
int atoi (const char * str);
【函数说明】atoi() 函数会扫描参数 str 字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过 isspace() 函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。
【返回值】返回转换后的整型数;如果 str 不能转换成 int 或者 str 为空字符串,那么将返回 0。
添加回答
举报