String转成int

本文介绍了一个Java程序示例,演示如何从键盘接收字符串并将其转换为整数,同时通过异常处理确保输入的有效性和程序稳定性。文章展示了如何判断输入是否为有效的整数格式,并在输入不合法时给出提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Scanner;
/*小练习
接收键盘录入字符串,把该字符串转换成int数值,使用nextline接收,思考如果用户键入的不是int数值,用异常处理合理的提示用户,并使程序不会终止
*/
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean Flag = true;
while (Flag) {
System.out.println(“请输入整数:”);
String s = sc.nextLine();
try {
System.out.println(“您输入的数据为:” + transform(s));
Flag = false;
} catch (InPutException e) {
System.out.println(e.getMessage());
}
}
}
public static int transform(String s) {
char[] arr = s.toCharArray();
int sum = 0;
//如果第一个字符为负号
if (arr[0] == ‘-’) {
for (int i = arr.length - 1; i >= 1; i–) {
if (arr[i] < ‘0’ || arr[i] > ‘9’) {
throw new InPutException(“输入的数据不是数字!”);
}
sum = (int) (sum + (arr[i] - 48) * Math.pow(10, (arr.length - i - 1)));
}
if(sum>-Integer.MIN_VALUE){
throw new InPutException(“输入的数据超出了int范围”);
}else {
return -sum;
}
//如果第一个字符为正常的数字
} else if (arr[0] >= ‘0’ && arr[0] <= ‘9’) {
for (int i = arr.length - 1; i >= 0; i–) {
if (arr[i] < ‘0’ || arr[i] > ‘9’) {
throw new InPutException(“输入的数据不是数字!”);
}
sum = (int) (sum + (arr[i] - 48) * Math.pow(10, (arr.length - i - 1)));
}
if(sum>Integer.MAX_VALUE){
throw new InPutException(“输入的数据超出了int范围”);
}else {
return sum;
}
} else {
throw new InPutException(“输入的数据不是数字!”);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值