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....
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,  ...
Write a program that will recognize and evaluate prefix expressions. First design and implement a class...
Write a program that will recognize and evaluate prefix expressions. First design and implement a class of prefix expressions. This class should contain methods to recognize and evaluate prefix expressions. This chapter discusses the algorithms you will need to implement these methods. Walls and Mirrors 3rd edition Chapter 6 Programming Practice 8. Programming Language: Java.
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, + ,...
Design and implement a C++ class called Module that handles information regarding your assignments for a specific module.
Design and implement a C++ class called Module that handles information regarding your assignments for a specific module. Think of all the things you would want to do with such a class and write corresponding member functions for your Module class. Your class declaration should be well-documented so that users will know how to use it.Write a main program that does the following: Declare an array of all your modules. The elements of the array must be of type Module....
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try and catch" statement to catch an exception if "empStatus == 1" hourly wage is not between $15.00/hr. and $25.00/hr. The keywords “throw” and “throws” MUST be used correctly and both keywords can be used either in a constructor or in a method. If an exception is thrown, the program code should prompt the user for the valid input and read it in. *NOTE*- I...
1. Design and implement a program that reads a series of integers from the user and...
1. Design and implement a program that reads a series of integers from the user and continually prints their average after every reading. The input stops when the user enters “stop” as the input value. Read each input value as a string, then check if it is “stop” or not. If the string is not “stop”, then, attempt to convert it to an integer using the Integer.parseInt method. If this process throws a NumberFormatException, meaning that the input is not...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT