2016-03-06 83 views
0

我不希望用戶輸入負值。我如何檢測負值和InputMismatchException?這是迄今爲止的代碼!該代碼似乎並不正確,並且無法確定問題出在哪裏。我想驗證用戶輸入以確保負數,字符串和double無效,並提示用戶輸入正確的數字,該數字應該是正整數。驗證倍數輸入

  do { 
       try { 
        System.out.println("How many " + teaName + " did you today?"); 
        if(input.hasNextInt() && (numberItem = input.nextInt()) > 0) { 
         istrue = false; 

         numberItem = input.nextInt(); 

        } 

       } catch (InputMismatchException e) { 
        input.nextLine(); 
        System.out.println("Please enter right number"); 
        istrue = true; 
       } 
       catch (NoSuchElementException e){ 
        System.out.println(" Please enter positive integers"); 
       } 
      } while (istrue); 
+0

負數不是'Scanner'拋出的異常,所以你不能將它添加到'catch'塊 – Idos

+0

你能發佈你的整個代碼嗎? –

回答

0
  do { 
      try { 
       System.out.println("How many " + teaName + " did you today?"); 
       if(input.hasNextInt()) { 
        if (numberItem = input.nextInt()) > 0) { 
         istrue = false; 

         numberItem = input.nextInt(); 
        } else { 
         throw new InputMisMatchException("negative num"); 
        } 

       } 

      } catch (InputMismatchException e) { 
       input.nextLine(); 
       System.out.println("Please enter right number"); 
       istrue = true; 
      } 
      catch (NoSuchElementException e){ 
       System.out.println(" Please enter positive integers"); 
      } 
     }while (istrue); 

這應該工作,我要做的就是拋出InputMismatchException時,當數字爲負。

+0

使用if語句只是「繼續」do while循環實際上比拋出異常並捕獲它要快 –

+0

另外,異常不應用於例程流控制 – tucuxi