本文共 953 字,大约阅读时间需要 3 分钟。
优化后的技术内容:
如何将整数字符串转换为整数并输出?以下是详细的解决方案。
程序思路
代码实现
package test020;public class Test020 { public static int string2Int(String num) { int result = 0; for (int i = 0; i < num.length(); i++) { char ch = num.charAt(i); if (ch < '0' || ch > '9') { System.out.println("包含非数字字符,无法转换为整数。"); return -1; } result = result * 10 + (ch - '0'); } return result; } public static void main(String[] args) { int a = string2Int("123"); int b = string2Int("4291"); System.out.println(a == 123 && b == 4291); }} 程序功能
注意事项
最佳实践
测试示例
输入:"123" -> 输出:123输入:"4291" -> 输出:4291输入:"abc" -> 输出:包含非数字字符,无法转换为整数。
转载地址:http://pbciz.baihongyu.com/