Question: Create a system with three classes (one of which is a test driver): 1. Create a CodeBot class ( CodeBot.java ) that has two private
Create a system with three classes (one of which is a test driver):
1. Create a CodeBot class (
CodeBot.java
) that has two
private
fields: className and
code (both are of type String).
o
Create a
no-arg
constructor that hard-codes the class name (e.g., Hello) and
initializes the code field with a string that represents a simple Java class that
displays something (e.g, hello, world) to standard output (e.g.,
"public
class Hello { public static void main(String[] args) {
System.out.println(\"hello, world\");}}").
o
Create another constructor that requires that the class name and code are
provided by the caller (i.e., a constructor with two String parameters).
o
Both constructors should call the private saveCode method (see below) to
save the code to the file system as part of constructing a CodeBot object.
o
Create a private helper method named saveCode that is based on Listing 12.14
on page 477 (Liang, 10th edition). This method should have a void return type
and result in a file being written in your projects root directory.
o
Create a public compile method that accepts no input arguments. If the class
name is not found in the code, the method will throw a CompilationException
with the message Class name must be found in code. Otherwise, it will print
out a message: The program
className.java
has compiled successfully.
2. Create a CompilationException class (
CompilationException.java
) that is a subclass
of Exception (i.e., a custom checked exception).
3. Create a CodeBotTest class (
CodeBotTest.java
) that instantiates a CodeBot object
using the no-arg constructor and then call the compile method. It should then create
another CodeBot object using the other constructor with className = Hello2 and
code =
"public class { public static void main(String[] args) {
System.out.println(\"hello, world\");}}"
and then call the compile method.
Here is a sample run:
Program Hello.java has compiled successfully.
Exception in thread "main" CompilationException: Class name must be found in code.
at CodeBot.compile(CodeBot.java:33)
at CodeBotTest.main(CodeBotTest.java:7)
The second time you run your program, it should print out the following message:
File Hello.java already exists.
If you want to generate the output in the sample run above again, you need to delete the
files -
Hello.java & Hello2.java
- and re-run your program.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
