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(“输入的数据不是数字!”);
}
String转成int
本文介绍了一个Java程序示例,演示如何从键盘接收字符串并将其转换为整数,同时通过异常处理确保输入的有效性和程序稳定性。文章展示了如何判断输入是否为有效的整数格式,并在输入不合法时给出提示。

被折叠的 条评论
为什么被折叠?



