I need help with a Java assignment: This problem requires three separate classes
ID: 3914535 • Letter: I
Question
I need help with a Java assignment:
This problem requires three separate classes, each in its own file.
class TeenInteger
has one type int data member intended to hold an integer from 13-19 inclusive.
has a constructor that can assign the integer's value, but only if it is in the range 13-19. If the value is out of range, a custom exception named BadTeenInputException should be thrown.
has a getter that returns the int data member. There is no setter.
class BadTeenInputException
extends class Exception, as all custom exceptions must do.
has one int data member for a "teen integer".
has a constructor like the one coded in Listing 12.10 on page 474.
has a getter for the int data member.
class TestTeenInteger
has a main method and a method named teenInfo that takes a TeenInteger argument.
In main
prompt the user to enter a "teen integer" int value.
in a try block, attempt to create a TeenInteger object with this int value and call teenInfo with this TeenInteger object as argument.
follow the try block with a catch block that catches a BadTeenInputException and displays an error message.
In teenInfo
print the valid "teen integer" and report it as either even or odd.
Sample Run 1
Enter a 'teen' integer (13-19) 14
14 is an even number
Sample Run 2
Enter a 'teen' integer (13-19) 17
17 is an odd number
Sample Run 3
Enter a 'teen' integer (13-19) 22
22 is an invalid teen integer. Must be 13-19, inclusive
Explanation / Answer
public class TeenInteger { private int number; public TeenInteger(int num) throws BadTeenInputException { if(num < 13 || num > 19) { throw new BadTeenInputException(num); } this.number = num; } public int getNumber() { return number; } } public class BadTeenInputException extends Exception { private int teenInteger; public BadTeenInputException(int teenInteger) { this.teenInteger = teenInteger; } public int getTeenInteger() { return teenInteger; } } import java.util.Scanner; public class TestTeenInteger { public static void teenInfo(TeenInteger integer) { if(integer.getNumber() % 2 == 0) { System.out.println(integer.getNumber() + " is an even number"); } else { System.out.println(integer.getNumber() + " is an odd number"); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a 'teen' integer (13-19) "); int num = in.nextInt(); try { TeenInteger teenInteger = new TeenInteger(num); teenInfo(teenInteger); } catch (BadTeenInputException e) { System.out.println(e.getTeenInteger() + " is an invalid teen integer. Must be 13-19, inclusive"); } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.