(NumberFormatException数字格式异常)编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户再次输入数字。

(NumberFormatException数字格式异常)编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户再次输入数字。

输入格式:

i 9 (第1次输入) l 8 (第2次输入) 5 6 (第3次输入)

输出格式:

Incorrect input and re-enter two integers: (第1次输出提示) Incorrect input and re-enter two integers: (第2次输出提示) Sum is 11 (输出结果)

输出样例:

i 9
l 8
5 6

输出样例:

Incorrect input and re-enter two integers:
Incorrect input and re-enter two integers:
Sum is 11

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main
{
    public static void main(String[]args)
    {
        Scanner in=new Scanner(System.in);
        int a,b;
        while(true)
        {
            try{
                a=in.nextInt();b=in.nextInt();
                System.out.println("Sum is "+(a+b));
            }
            catch(InputMismatchException e)
            {
                in.nextLine();
                System.out.println("Incorrect input and re-enter two integers:");
                continue;
            }
            break;
        }
    }
    }
  • 12
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
这个程序的流程如下: 1. 提示用户输入一个整数。 2. 读取用户输入的第一个整数。如果输入不是一个合法的整数提示用户再次输入,并重复步骤1。 3. 提示用户输入第二个整数。 4. 读取用户输入的第二个整数。如果输入不是一个合法的整数提示用户再次输入,并重复步骤3。 5. 计算两个整数的和。 6. 输出计算结果。 整个过程可以用一个while循环实现,每次循环读取一个整数并检查其合法性,直到读取两个合法的整数为止。代码可能如下所示: ```java import java.util.Scanner; public class AddTwoNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num1 = 0; int num2 = 0; boolean validInput = false; while (!validInput) { System.out.print("Enter the first number: "); String input = scanner.nextLine(); try { num1 = Integer.parseInt(input); validInput = true; } catch (NumberFormatException e) { System.out.println("Invalid input. Please enter an integer."); } } validInput = false; while (!validInput) { System.out.print("Enter the second number: "); String input = scanner.nextLine(); try { num2 = Integer.parseInt(input); validInput = true; } catch (NumberFormatException e) { System.out.println("Invalid input. Please enter an integer."); } } int sum = num1 + num2; System.out.println("The sum is: " + sum); } } ``` 这个程序首先创建一个Scanner对象,用于读取用户输入。然后定义两个整数变量num1和num2,用于存储用户输入两个整数。接下来进入一个while循环,要求用户输入一个整数,并将用户输入的字符串转换为整数。如果转换失败,则提示用户再次输入;如果转换成功,则将num1赋值为转换后的整数,并将validInput设为true,表示输入合法。循环结束后,程序进入下一个while循环,要求用户输入第二个整数,并采用类似的方法检查其合法性。最后,程序计算两个整数的和,输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值