【问题标题】:I am new to coding. if user give wrong input how can we ask to reenter input without exiting code?我是编码新手。如果用户输入错误,我们如何要求在不退出代码的情况下重新输入输入?
【发布时间】:2023-03-23 03:15:02
【问题描述】:

我的问题是,当用户输入错误时,它会抛出异常消息“错误输入”并退出代码。我想再次要求输入输入而不退出代码。我尝试了while循环,但我没有做对,所以请帮助我的疑问。

import java.util.Scanner;

public class A{

    public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);
      
      try {  System.out.println("enter");
      int a=sc.nextInt();
      int b=sc.nextInt();
           System.out.println(a+b);
          
      } catch (Exception e) {
          //TODO: handle exception
          System.out.println("wrong input");
          System.out.println("enter again");
         
      }
   }
}

【问题讨论】:

  • 你确定你了解什么是while循环吗?您的代码示例似乎根本没有以任何方式循环...
  • @sittsering 然后请删除您的评论

标签: java loops exception user-input


【解决方案1】:

使用 while 循环和中断。

while (true)
{
    try {
        System.out.println("enter");
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.println(a + b);
        break;
       } catch (Exception e) {
            System.out.println("wrong input");
            System.out.println("enter again");
            sc.nextLine();
       }
}

只有当ab的值都输入正确时,才会跳出while循环,否则会一直循环。

【讨论】:

  • 谢谢。我没有添加 sc.nextLine();同时尝试while循环
猜你喜欢
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2021-03-27
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
相关资源
最近更新 更多