2013-02-24 2 views
0

Я не прошу никого выполнять свою работу. Мне просто нужна небольшая помощь в решении этого несоответствия. Это моя программа:Попробуйте поймать петли

import java.util.InputMismatchException; 
import java.util.Scanner; 
class FibonacciNumbers { 

    FibonacciNumbers()   //default constructor 
    { 
    } 

    Scanner in = new Scanner(System.in); 

    public int fOf(int n) 
    { 

     if (n == 0)      //the base case 
     { 

      return 0; 

     } 
     else if (n==1) 
     { 

      return 1; 
     } 

     else 
     { 

      return fOf(n-1)+fOf(n-2); 
     } 
     } 

public static void main(String[] args) 
    { 
     FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object 

     Scanner in = new Scanner(System.in); 
     String userInput; 
     int n = 0; 
     boolean IsRepeat = true ; 
     boolean isQuit; 
     boolean checkException = false; 

    isQuit = false; 

    while (!isQuit) 
    { 


try { 

    { 

     System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): "); 


     n = in.nextInt(); 
     System.out.print("The Fibanocci number for "+n+" is: "); 
     n = fNumbers.fOf(n); 
     System.out.println(n); 

     System.out.print("Do you want to run again? Press 'N' for No or anything else to continue: "); 

     userInput = in.next(); 

     if(userInput.equalsIgnoreCase("N")) 
      { 
       isQuit = true; 
       System.out.println("Good-bye!"); 
      } 
     else 

     { 
     IsRepeat = true; 
     } 
     } 
    } 

catch(InputMismatchException ex) { 
      userInput = in.nextLine(); 

      if ((userInput.charAt(0) == 'q') || (userInput.charAt(0) == 'Q')) 
      { 

        isQuit = true; 
        System.out.println("Good-bye!"); 

      } 

      else { 
       checkException = true; 
       IsRepeat = true; 
       System.out.println("Invalid entry, Try again!"); 
       }  
    } 

    catch (ArrayIndexOutOfBoundsException a) 
     { 
      n = in.nextInt(); 
      if (n<0 || n>46) 
         { 
          System.out.println("Invalid entry! Please enter an integer that is greater than 0 but less than 46 :"); 
          checkException = false;//sets boolean value to false, continues the loop 


         } 
         else 
          { 
          IsRepeat = true; 
          } 
    } 
    } 
} 
} 

Я сделал все, что я получил все, чтобы работать, но в этой части она не собирается, как я хочу, чтобы запустить:

catch (ArrayIndexOutOfBoundsException a) 
     { 
      n = in.nextInt(); 
      if (n<0 || n>46) 
         { 
          System.out.println("Invalid entry! Please enter an integer that is greater than 0 but less than 46 :"); 
          checkException = false;//sets boolean value to false, continues the loop 


         } 
         else 
          { 
          IsRepeat = true; 
          } 
    } 

Когда я запускаю его, если пользователь вводит выше 46 или ниже 0, тогда попросите их ввести другой вход, но он просто выполняет математику. Это не будет так, как я написал программу.

+0

Как вы ожидаете, что бросить 'ArrayIndexOutOfBoundsException'? Вы не используете в своем коде массивы. Почему вы даже беспокоитесь, основывая свою логику приложений на исключениях? Это бесполезно сложно. – toniedzwiedz

+0

Знаете ли вы, что я мог бы поставить вместо ArrayIndexOutOfBoundsException – user2059140

+0

@ user2059140, просто проверьте, не превышает ли число за пределами требуемого диапазона (1-46), и распечатайте сообщение и продолжите цикл. – toniedzwiedz

ответ

1

Он выбрасывает «java.lang.StackOverflowError» вместо «ArrayIndexOutOfBoundsException».

Лучше всего было бы, чтобы поймать неверный ввод в

System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): "); 
n = in.nextInt(); 

вы можете установить «п = in.nextInt();» в делать - while- петли,

как:

do { 
    ask for number 
} while (check if number is correct); 
+0

Я не понимаю, что вы пытаетесь сказать. Я положил 'System.out.print (« Введите число, которое вы хотите преобразовать в Fibanocci ('q' to quit): "); n = in.nextInt(); System.out.print («Число Fibanocci для« + n + »:»); n = fNumbers.fOf (n); System.out.println (n); 'в цикле do и остальном в цикле while? – user2059140

+0

Это только один цикл. Часть между «{» и «}» будет повторяться так часто, как часть между «(« и »)« истинна ». Поэтому, если вы используете «do {System.out.print (« Введите число, которое вы хотите преобразовать в Fibanocci («q», чтобы выйти): »); n = in.nextInt();} while (n < 0 || n > 46); " он будет продолжать запрашивать номер, пока он не станет между 0 и 46 (оба включительно) – ageh

+0

Спасибо, сейчас это работает! – user2059140