Я не прошу никого выполнять свою работу. Мне просто нужна небольшая помощь в решении этого несоответствия. Это моя программа:Попробуйте поймать петли
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, тогда попросите их ввести другой вход, но он просто выполняет математику. Это не будет так, как я написал программу.
Как вы ожидаете, что бросить 'ArrayIndexOutOfBoundsException'? Вы не используете в своем коде массивы. Почему вы даже беспокоитесь, основывая свою логику приложений на исключениях? Это бесполезно сложно. – toniedzwiedz
Знаете ли вы, что я мог бы поставить вместо ArrayIndexOutOfBoundsException – user2059140
@ user2059140, просто проверьте, не превышает ли число за пределами требуемого диапазона (1-46), и распечатайте сообщение и продолжите цикл. – toniedzwiedz