Question

In: Computer Science

1) Design an implement a program that created and exception class called StringTooLongException, designed to be...

1) Design an implement a program that created and exception class called StringTooLongException, designed to be thrown when a string is discovered that has too many characters in it. Create a driver that reads in strings from the user until the user enters DONE. If a string that has more then 5 characters is entered, throw the exception. Allow the thrown exception to terminate the program

2) Create a class called TestScore that has a constructor that accepts an array of test scores as its argument. The class should have a method that returns the average of the test scores. If any test score in the array is negative or greater than 100, the class should throw an IllegalArgumentException. Create a driver to make the array and demonstrate the TestScore class.

3) Create a class called InvalidTestScore. Modify your TestScores class so that it throws an InvalidTestScore exception if any of the test scores in the array are invalid.

Solutions

Expert Solution

Q 1: StringTooLongException:

Explanation part is given below the program in the form of table

import java.util.*;
class StringTooLongException extends Exception
{
public StringTooLongException(String s)
{
super(s);
}
public String toString(){
return ("Too many Characters in the given string") ;
}
}
public class Main
{
   public static void main(String[] args) {
   String str = "",entirestring = "";
Scanner sc = new Scanner(System.in);
for(int i=1;i>0;i++){
str = sc.nextLine();
  
if(str.equals("DONE")){
break;
}
else
entirestring += str;
}
   System.out.println(entirestring);
   System.out.println(entirestring.length());
   try{
if(entirestring.length()>=20)

throw new StringTooLongException(entirestring);

}
catch(StringTooLongException exception){
System.out.println(exception);
}
}
}

Explanation for Q1:

Code

Explanation

class StringTooLongException extends Exception
{
public StringTooLongException(String s)
{
super(s);
}
public String toString(){
return ("Too many Characters in the given string") ;
}
}

User defined exception class which inherits from “Exception” class.

toString() is used to provide user defined message when this class is called in “catch” block in the main function

Main()

public static void main(String[] args) {
   String str = "",entirestring = "";
Scanner sc = new Scanner(System.in);
for(int i=1;i>0;i++){
str = sc.nextLine();
  
if(str.equals("DONE")){
break;
}
else
entirestring += str;
}
   System.out.println(entirestring);
   System.out.println(entirestring.length());

Obtain the input from the user and store each input in “entirestring”. The input is obtained using “for” loop unless “DONE” is encountered.

entirestring and its length are printed for the sake of understanding

try{
if(entirestring.length()>=20)

throw new StringTooLongException(entirestring);

}
catch(StringTooLongException exception){
System.out.println(exception);
}

This is doing the actual logic of checking the length of the user input. Here I have assume if length>20, then throw the error.

Error is thrown using

throw new StringTooLongException(entirestring);

The above statement will reach the catch block and it will print the message from toString() of StringTooLongException class.

Q.2 Illegal Argument Exception:

import java.util.*;
class TestScores
{
private double[] scores;
double totalscore = 0;

public TestScores(double arrayscore[])
{
for (int i = 0; i < arrayscore.length; i++)
{
scores = new double[arrayscore.length];
if (arrayscore[i] < 0 || arrayscore[i] > 100)
{
throw new IllegalArgumentException("Bad scores" + "\n\tInvalid score found." + "\n\tPosition: " + (i+1) + ", Score given: " + arrayscore[i]);
}
else
{
scores[i] = arrayscore[i];
totalscore += arrayscore[i];
}
}
}

public double getAverageScore()
{
return totalscore / scores.length;
}
}
public class Main
{
   public static void main(String[] args) {
   double[] testScores1 = { 97.5, 66.7, 88.0, 10.0, 99.0 };
double[] testScores2 = { 97.5, 66.7, -88.0, 100.0, 99.0 };
TestScores test=null;

try
{
test = new TestScores(testScores1);
}
catch (IllegalArgumentException e)
{
System.out.println(e.getMessage());
}

try
{
test = new TestScores(testScores2);
}
catch (IllegalArgumentException e)
{
System.out.println(e.getMessage());
}

System.out.print("Good scores"+ "\n\tThe average of the good scores is " + test.getAverageScore());
}
}

Explanation for Q2

Code

Explanation

class TestScores
{
private double[] scores;
double totalscore = 0;

public TestScores(double arrayscore[])
{
for (int i = 0; i < arrayscore.length; i++)
{
scores = new double[arrayscore.length];
if (arrayscore[i] < 0 || arrayscore[i] > 100)
{
throw new IllegalArgumentException("Bad scores" + "\n\tInvalid score found." + "\n\tPosition: " + (i + 1) + ", Score given: " + arrayscore[i]);
}
else
{
scores[i] = arrayscore[i];
totalscore += arrayscore[i];
}
}
}

public double getAverageScore()
{
return totalscore / scores.length;
}
}

User Define method Test Score to through IllegalArgument Exception.

As said in the question an array is used and iterated to check for the given condition.

If the condition violates, it throws error. Otherwise it will calculate the total score.

getAverageScore() is used to return the total score of that object

double[] testScores1 = { 97.5, 66.7, 88.0, 10.0, 99.0 };
double[] testScores2 = { 97.5, 66.7, -88.0, 100.0, 99.0 }; // Good scores is actually bad
TestScores test=null;

This is to declare and initialize array with varied score

try
{
test = new TestScores(testScores1);
}
catch (IllegalArgumentException e)
{
System.out.println(e.getMessage());
}

This will not through Illegal Argument Exception because the score contains correct values.

try
{
test = new TestScores(testScores2);
}
catch (IllegalArgumentException e)
{
System.out.println(e.getMessage());
}

testScore2 contains illegal values hence this will throw Exception (user defined).

Answer for Q3:

import java.util.*;
class InvalidTestScoreException extends Exception
{
public InvalidTestScoreException(String s)
{
super(s);
}   
public String toString(){
return ("There is an invalid score in the given list of score") ;
}

}
class TestScores
{

private double[] scores;
double totalscore = 0;

public TestScores(double arrayscore[])
{
try
{
for (int i = 0; i < arrayscore.length; i++)
{
scores = new double[arrayscore.length];
if (arrayscore[i] < 0 || arrayscore[i] > 100)
{
  
throw new InvalidTestScoreException("Invalid score");
}
else
{
scores[i] = arrayscore[i];
totalscore += arrayscore[i];
}
}
}
catch(InvalidTestScoreException e)
{
System.out.println(e.getMessage());
}
}

public double getAverageScore()
{
return totalscore / scores.length;
}
}
public class Main
{
   public static void main(String[] args) {
   double[] testScores1 = { 97.5, 66.7, 88.0, 10.0, 99.0 };
double[] testScores2 = { 97.5, 66.7, -88.0, 100.0, 99.0 };
TestScores test=null;
test = new TestScores(testScores1);
test = new TestScores(testScores2);
System.out.print("Good scores"+ "\n\tThe average of the good scores is " + test.getAverageScore());
}
}

Explanation:

Same as previous only following modification done:

a) New class called InvalidTestScoreException added

b) try catch block removed from Main()

c) Test Score class handles the exception


Related Solutions

EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates...
EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates an exception class called ManyCharactersException, designed to be thrown when a string is discovered that has too many characters in it. Consider a program that takes in the last names of users. The driver class of the program reads the names (strings) from the user until the user enters "DONE". If a name is entered that has more than 20 characters, throw the exception....
EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates  ...
EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to be thrown when a   string is discovered that has too many characters in it. Consider a   program that   takes   in the last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,   throw   the   exception.  ...
JAVA Specify, design, and implement a class called PayCalculator. The class should have at least the...
JAVA Specify, design, and implement a class called PayCalculator. The class should have at least the following instance variables: employee’s name reportID: this should be unique. The first reportID must have a value of 1000 and for each new reportID you should increment by 10. hourly wage Include a suitable collection of constructors, mutator methods, accessor methods, and toString method. Also, add methods to perform the following tasks: Compute yearly salary - both the gross pay and net pay Increase...
Design and implement a class called circle_location to keep track of the position of a single...
Design and implement a class called circle_location to keep track of the position of a single point that travels around a circle. An object of this class records the position of the point as an angle, measured in a clockwise direction from the top of the circle. Include these public member functions: • A default constructor to place the point at the top of the circle. • Another constructor to place the point at a specified position. • A function...
C++ program homework question 1 1. Create and implement a class called clockType with the following...
C++ program homework question 1 1. Create and implement a class called clockType with the following data and methods (60 Points.): Data: Hours, minutes, seconds Methods: Set and get hours Set and get minutes Set and get seconds printTime(…) to display time in the form of hh:mm:ss default and overloading constructor Overloading Operators: << (extraction) operator to display time in the form of hh:mm:ss >> (insertion) operator to get input for hours, minutes, and seconds operator+=(int x) (increment operator) to...
Create a java program that: - Has a class that defines an exception -Have that exception...
Create a java program that: - Has a class that defines an exception -Have that exception throw(n) in one method, and be caught and handled in another one. -Has a program that always continues even if incorrect data is entered by the user -has a minimum of 2 classes in it
JAVA - Design and implement a class called Flight that represents an airline flight. It should...
JAVA - Design and implement a class called Flight that represents an airline flight. It should contain instance data that represent the airline name, the flight number, and the flight’s origin and destination cities. Define the Flight constructor to accept and initialize all instance data. Include getter and setter methods for all instance data. Include a toString method that returns a one-line description of the flight. Create a driver class called FlightTest, whose main method instantiates and updates several Flight...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a  ...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to   be   thrown   when   a   string   is   discovered   that   has   too   many   characters   in   it. Consider   a   program   that   takes   in   the   last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,  ...
Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class converts an...
Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class converts an infix expression to a postfix expression. The PostFixCalculator class evaluates a postfix expression. This means that the expressions will have already been converted into correct postfix form. Write a main method that prompts the user to enter an expression in the infix form, converts it into postfix, displays the postfix expression as well as it's evaluation. For simplicity, use only these operators, + ,...
Write in drjava Problem Design and implement these 4 files: A parent class called Plant with...
Write in drjava Problem Design and implement these 4 files: A parent class called Plant with name (eg Rose, Douglas Fir) and lifespan (could be in days, weeks, months or years) attributes Tree inherits from Plant and adds a height attribute Flower inherits from Plant and adds a color attribute A driver file to test the 3 classes above. The classes described in #1, 2 and 3 above should have the usual constructors (default and parameterized), get (accessor) and set...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT