In: Computer Science
: Design and implement class Radio to represent a radio object. The class defines the following attributes (variables) and methods:
Assume that the station and volume settings range from 1 to 10.
The radio station is X and the volume level is Y. Where X and Y are the values of variables station and volume. If the radio is off, the message is: The radio is off.
Now design and implement a test program to create a default radio object and test all class methods on the object in random order. Print the object after each method call and use meaningful label for each method call as shown in the following sample run.
Sample run:
Turn radio on:
The radio station is 1 and the volume level is 1.
Turn volume up by 3:
The radio station is 1 and the volume level is 4.
Move station up by 5:
The radio station is 6 and the volume level is 4.
Turn volume down by 1:
The radio station is 6 and the volume level is 3.
Move station up by 3:
The radio station is 9 and the volume level is 3.
Turn radio off.
The radio is off.
Turn volume up by 2: The radio is off.
Turn station down by 2: The radio is off.
Requirements include toString() method which is in JAVA. Hence writing a JAVA Program.
JAVA Program:
import java.io.*;
class Radio {
private int station,volume;
private boolean on;
public Radio(){
this.station = 1;
this.volume = 1;
this.on = false;
}
public int getStation(){
return this.station;
}
public int getVolume(){
return this.volume;
}
public void turnOn(){
System.out.println("Turn radio on:");
this.on = true;
}
public void turnOff(){
System.out.println("Turn radio off:");
this.on = false;
}
public void stationUp(int stat){
System.out.println("Move station up by "+stat+":");
if(this.on)
{
if(this.station+stat>10)
System.out.println("Station Unavailable!!");
else{
this.station+=stat;
}
}
}
public void stationDown(int stat){
System.out.println("Move station down by "+stat+":");
if(this.on){
if(this.station-stat<0)
System.out.println("Station Unavailable!!");
else{
this.station-=stat;
}
}
}
public void volumeUp(int vol){
System.out.println("Turn volume up by "+vol+":");
if(this.on)
{
if(this.volume+vol>10)
System.out.println("Volume Unavailable!!");
else{
this.volume+=vol;
}
}
}
public void volumeDown(int vol){
System.out.println("Turn volume down by "+vol+":");
if(this.on){
if(this.volume-vol<0)
System.out.println("Volume Unavailable!!");
else{
this.volume-=vol;
}
}
}
public String toString(){
if(this.on)
return "\tThe radio station is "+getStation()+" and the volume
level is "+getVolume()+".\n";
else
return "\tThe radio is off.";
}
public static void main (String[] args) {
Radio r = new Radio();
r.turnOn();
System.out.println(r);
r.volumeUp(3);
System.out.println(r);
r.stationUp(5);
System.out.println(r);
r.volumeDown(1);
System.out.println(r);
r.stationUp(3);
System.out.println(r);
r.turnOff();
System.out.println(r);
r.volumeUp(2);
System.out.println(r);
r.stationDown(2);
System.out.println(r);
}
}
Output: