Подскажите ошибку в Java
Подскажите что нужно делать чтобы в one_turn catch вернул ошибку если х не равно 1 или 2.
public class Main {
// Random number function in range of 10 - 20
public static int random_number_gen(){
int number = 10 + (int)(Math.random() * ((20 - 10) + 1));
return number;
}
static int users_turn = 1;
public static int get_from_player(){
System.out.println("Player" + users_turn + " enter either 1 or 2 ");
Scanner asking_for_guess = new Scanner(System.in);
int data = Integer.parseInt(asking_for_guess.nextLine());
return data;
}
public static int one_turn(){
try{
int x = get_from_player();
if (x == 1 || x == 2) {
return x;
}
else{
return 0;
}
}
catch(Exception err){
System.out.println("Please provide an integer, either 1 or 2 !");
return one_turn();
}
}
Ответы (1 шт):
Автор решения: Sypchik
→ Ссылка
Вы можете выбрасывать исключения самостоятельно.
public static int one_turn() {
int x = get_from_player();
if (x == 1 || x == 2) {
return x;
} else {
throw new RuntimeException("incorrect digit!");
}
}