0

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

问题是当我运行我的简单代码时 - 你可以选择一个数字,没关系,循环工作正常。当您选择 0 时,它也可以工作(运行完成),但是当您输入一个字母或任何字符串时 - 有一个问题......即使我尝试输入另一个值,异常也会不停地循环。

PS。我需要在这里使用扫描仪,所以请不要写读者等 - 只是如何解决这个特定问题。

干杯,

这是代码(仅主要):

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));   

}
4

3 回答 3

0

已编辑

这样做

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));   

    }
于 2014-02-20T08:09:39.090 回答
0

尝试这个:

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");

}
于 2014-02-20T08:10:54.557 回答
0

问题是当你说 -

丹麦人 = sc.nextInt();

在上面的行中,如果您输入的不是数字,它将引发异常输入不匹配。让我们了解这条线的作用。实际上有两件事——

首先 sc.nextInt() 读取一个整数,只有在成功完成此任务时,它才会将该整数值分配给变量 dane。但是在读取一个整数时,它会抛出一个 InputMismatchException,因此分配从未发生过,但 dane 的 previos 值不是扫描仪读取的新值,所以 dane 仍然不等于 0。所以循环继续。

我希望它有所帮助。

于 2014-02-20T08:12:46.280 回答