It is necessary to calculate and display the factorial of the number specified on the command line. Handle possible user input errors with try, catch, and throw. I only managed to find factor numbers without try, catch and throw operators:

public class Test { public static void main(String args[]) { int n; do { Scanner scan = new Scanner(System.in); System.out.print("Введите факториал натурально числа n : "); n = scan.nextInt(); int result = 1; for (int i = 2; i <= n; i++) result *= i; System.out.println(result); if (n == 0 || n == 1) System.out.println(result); if(n < 0) System.out.println("Вы ввели отрицательный факториал!"); } while (n < 0);{System.out.println("Конец");} } } 

Waiting for help!

  • Read about exceptions, help yourself - Vladimir Martyanov
  • Sorry, but I would not have asked for help here if I could help myself, read and try, but nothing happens. - Dobriachok
  • And what is the problem to write throw instead of displaying a message about negative input, for example? - Vladimir Martyanov
  • one
    It is somehow not customary to decide for their other tasks, if they themselves have not done anything to solve them ... - Vladimir Martyanov
  • 2
    You learn, and you learn. The sense from writing code for you will be zero. If you do not need this programming - go to the freelancers. - Vladimir Martyanov

1 answer 1

 int n = 0; while (true) { try { Scanner scan = new Scanner(System.in); System.out.print("Введите факториал натурально числа n : "); n = scan.nextInt(); break; } catch (java.util.InputMismatchException e) { System.out.println("Некорректный ввод!"); } } do { int result = 1; for (int i = 2; i <= n; i++) result *= i; System.out.println(result); if (n == 0 || n == 1) System.out.println(result); if (n < 0) System.out.println("Вы ввели отрицательный факториал!"); } while (n < 0); System.out.println("Конец"); 

If you separate the user input from the calculations, then everything is easier. But in any case, your way is bad. The code of the simplest algorithm is written quite confusing. An int factor is used for the factorial value. Try to calculate factorial 20 and see what happens and it's only 20. I would understand long, but in this case even he will not save you. Try using biginteger. And try to write it with the help of recursion, but this is for general development, and not for real life. Recursion when calculating factorial at large values ​​will reflect for a long time, and maybe throw an exception. Understand what I wrote, it will be pretty good. Good luck