Question: Modify the code so that instead of always saying Hello, the code will randomly select from among several possible greetings. To accomplish this you will
Modify the code so that instead of always saying Hello, the code will randomly select from among several possible greetings. To accomplish this you will add a private field, which is an ArrayList of Strings. This ArrayList will contain the possible greetings. You will also want to include a random number generator which is an instance of the1 Random class. Because each greeter object does not need its own random number generator, you will want to make the generator static so that it is shared among all Greeter objects.
Here is the code:
Greeter.java
/**
A class for producing simple greetings. (Revised to include sayGoodbye)
*/
/**
* @author MikeDelVecchio
*
*/
public class Greeter
{
/**
Constructs a Greeter object that can greet a person or
entity.
@param aName the name of the person or entity who should
be addressed in the greetings.
*/
public Greeter(String aName)
{
name = aName;
}
/**
swaps the names of the greeter object and other instance
*/
public void swapNames(Greeter other)
{
String temp;
temp = this.name;
this.name = other.name;
other.name = temp;
}
/**
Greet with a "Hello" message.
@return a message containing "Hello" and the name of
the greeted person or entity.
*/
public String sayHello()
{
return "Hello, " + name + "!";
}
/**
Greet with a "Goodbye" message.
@return a message containing "Goodbye" and the name of
the greeted person or entity
*/
public String sayGoodbye()
{
return "Goodbye, " + name + "!";
}
private String name;
}
GreeterTester.java
/**
A class for testing the methods of class Greeter.
*/
public class GreeterTester
{
/**
This method creates a greeter object and prints the strings
produced by calling sayHello, sayGoodbye, and swapNames with that object.
@param args unused
*/
public static void main(String[] args)
{
Greeter worldGreeter = new Greeter("World");
Greeter otherGreeter = new Greeter("Space");
String greeting = worldGreeter.sayHello();
String greeting2 = worldGreeter.sayGoodbye();
System.out.println(greeting);
System.out.println(greeting2);
worldGreeter.swapNames(otherGreeter);
String greeting3 = worldGreeter.sayHello();
System.out.println(greeting3);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
