首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >InputMismatchException在环

InputMismatchException在环
EN

Stack Overflow用户
提问于 2014-02-20 08:02:50
回答 3查看 697关注 0票数 0

我试图为我的问题找到一个解决办法,但在实践中却找不到一个有效的解决办法。所以请,如果你不确定你知道解决方案是什么,不要回答。我真的需要具体的帮助。

问题是,当我运行我的简单代码-你可以选择一个数字,这很好,循环工作良好。当您选择0,它也工作(运行结束),但当你放一个字母或任何字符串-有一个问题.一个异常不停地循环,即使我尝试输入另一个值。

PS。我需要在这里使用扫描仪,所以请不要写关于读者等-如何解决这个具体的问题。

干杯,

下面是代码(只有main):

代码语言:javascript
复制
public static void main(String[] args) {
    // TODO code application logic here
    Scanner sc = new Scanner(System.in);
    int dane = -1 ;

     boolean keepLooping;   //if you delete this works the same with same problem
do  
{    
    keepLooping = false;
    try
    {

            System.out.println("Pick a number:");
            dane = sc.nextInt();


    }catch (InputMismatchException e)
      {
          System.out.println("Your exception is: " + e);
          keepLooping = false;
      }  
    System.out.println("Out from exception");

}while ((dane != 0)||(keepLooping == true));   

}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-02-20 08:10:54

试试这个:

代码语言:javascript
复制
public static void main(String[] args) {
    // TODO code application logic here
    Scanner sc = new Scanner(System.in);
    int dane = -1 ;

     boolean keepLooping = true;   //if you delete this works the same with same problem
while(keepLooping && dane != 0)  
{    

    System.out.println("Pick a number:");
try
{ 

        dane = Integer.parseInt(sc.next());


}catch (NumberFormatException e)
  {
       keepLooping = true;
  }  
System.out.println("Out from exception");

}
票数 0
EN

Stack Overflow用户

发布于 2014-02-20 08:09:39

编辑的

就像这样

代码语言:javascript
复制
public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int dane = -1 ;

         boolean keepLooping;   //if you delete this works the same with same problem
    do  
    {    
        keepLooping = false;
        try
        {

                System.out.println("Pick a number:");
                dane = sc.nextInt();


        }catch (InputMismatchException e)
          {
              System.out.println("Your exception is: " + e);
              keepLooping = false;
              dane = sc.nextInt();
          }  
        System.out.println("Out from exception");

    }while ((dane != 0)||(keepLooping == true)&&(dane!=0));   

    }
票数 0
EN

Stack Overflow用户

发布于 2014-02-20 08:12:46

问题是当你说-

dane = sc.nextInt();

在上面的行中,如果您提供了一个数字以外的任何输入,它将抛出异常输入不匹配。让我们理解这一行的作用。实际上有两件事-

首先,sc.nextInt()读取一个整数,并且只有在此任务成功完成后,它才会将该整数值赋值给变量dane。但是在读取整数时,它会抛出一个InputMismatchException,这样赋值就不会发生,然而dane有它的previos值,而不是扫描器读取的新值,所以dane仍然不等于0。循环还在继续。

希望能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21901665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档