how can this code be modified to a try-catch instead of an if-else? /* * To chan
ID: 3903107 • Letter: H
Question
how can this code be modified to a try-catch instead of an if-else?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package guessing;
/**
*
* @author Alexandrea
*/
import java.util.Random;
import java.util.Scanner;
public class Guessing {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int number = random.nextInt(100);
int guess = -1;
while (guess!=number) {
System.out.print("Guess a number between 1 and 100: ");
guess = scanner.nextInt();
if (guess<number) {
System.out.println("Too low! Try again!");
} else if (guess>number) {
System.out.println("Too high! Try again!");
} else {
System.out.println("Winner! The number is " + number);
}
}
}
}
Explanation / Answer
You can throw exception for inavlid inputs as shown below.
package guessing;
/**
*
* @author Alexandrea
*/
import java.util.Random;
import java.util.Scanner;
public class Guessing {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int number = random.nextInt(100);
int guess = -1;
while (guess!=number) {
try {
System.out.print("Guess a number between 1 and 100: ");
guess = scanner.nextInt();
if (guess<number)
throw new IllegalArgumentException("Too low! Try again!");
if (guess>number)
throw new IllegalArgumentException("Too high! Try again!");
System.out.println("Winner! The number is " + number);
} catch(IllegalArgumentException e) {
e.printStackTrace();
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.