Почитал про оную, решил воспроизвести в коде для улучшения понимания. В моём коде (метод factorial2) в return IDEA ругается и предлагает объявить локальную переменную. В коде от чат гпт в подобном случае всё ок. Помогите разобраться, почему в одном случае ок, а в другом подчёркивается.
![]()
public class Chapter3 {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter number to calculate factorial:");
try {
int number = Integer.parseInt(reader.readLine());
int number2 = Integer.parseInt(reader.readLine());
System.out.println(factorial2(number, number2));
} catch (IOException e) {
System.out.println("error");
}
catch (NumberFormatException e) {
System.out.println("wrong number format");
}
//для вызова метода от чатгпт
/* int n = 12;
int result = factorial3(n); // вызов с n = 5
System.out.println(result); // вывод 120*/
}
private static long factorial2 (int num, int one) {
one = 1;
if (num == 1 | num == 0) {
return one;
}else {
return (num - 1, num * one); //num * one подчеркнуто, предлагается Introduce local variables или Remove expression
}
}
// ниже код от чат гпт
// Хвостовая рекурсивная функция для вычисления факториала
public static int factorial3(int n) {
return factorialHelper(n, 1);
}
// Вспомогательная функция для реализации хвостовой рекурсии
private static int factorialHelper(int n, int accumulator) {
if (n == 0) {
return accumulator;
} else {
return factorialHelper(n - 1, n * accumulator);
}
}
}