Created
March 28, 2017 15:33
-
-
Save stden/a3bb4168cba172cc4ee95325c223b230 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Factorial { | |
public static void main(String[] args) { | |
byte i = enterValue(); // Ввод данных | |
long result = factorial(i); // Вычисления | |
System.out.println(result); // Вывод ответа | |
} | |
private static byte enterValue() { | |
byte i = 0; | |
// Переменная incorrect используется только внутри этой функции, и пусть она будет внутри её и объявлена | |
boolean incorrect = true; | |
while (incorrect) { | |
try { | |
Scanner in = new Scanner(System.in); | |
System.out.println("Введите целое число от 0 до 20 включительно"); | |
i = in.nextByte(); | |
if ((i < 0) || (i > 20)) { | |
System.out.println("Введено число вне диапазона от 0 до 20"); | |
} else { | |
incorrect = false; | |
// По факту, нам переменная incorrect вообще не нужна, т.к. как только пользователь вводит | |
// корректное число => мы выходим из программы | |
return i; | |
} | |
} catch (InputMismatchException e) { | |
System.out.println("Введенно некоректное значение!"); | |
incorrect = true; | |
} | |
} | |
return i; | |
} | |
/** | |
* Вычисление факториала | |
*/ | |
private static long factorial(byte count) { // На практике часто используют int (не стараются ужать до одного байта) | |
long result = 1; | |
for (byte i = 1; i <= count; i++) { | |
result *= i; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment