Skip to content

Instantly share code, notes, and snippets.

@bytecodeman bytecodeman/TV.java Secret
Last active Oct 4, 2019

Embed
What would you like to do?
CSC-220 The TV class development code using ArrayLists to keep track of IDs
package chapter9;
public class TestTV {
public static void main(String[] args) {
TV tv1 = new TV("1");
tv1.turnOn();
tv1.setChannel(30);
tv1.setVolumeLevel(5);
TV tv2 = new TV("2");
tv2.turnOn();
tv2.channelUp();
tv2.channelUp();
tv2.volumeUp();
for (int i = 0; i < 100000; i++) {
do {
try {
TV tv3 = new TV();
System.out.println(tv3);
break;
}
catch (Exception ex) {
}
} while (true);
}
System.out.println(tv1);
System.out.println(tv2);
}
}
package chapter9;
import java.util.*;
public class TV {
private String id;
private int channel;
private int volumeLevel;
private boolean on;
private static ArrayList<String> serialnos = new ArrayList<>();
private static String autoGenerateID() {
return String.format("Samsung-%07d", (int)(Math.random() * 10000) + 1);
}
public TV() {
this(autoGenerateID());
}
public TV(String id) {
if (!serialnos.contains(id)) {
serialnos.add(id);
this.id = id;
this.channel = 1;
this.volumeLevel = 1;
this.on = false;
}
else {
throw new RuntimeException("Duplicate TV Serial No: " + id);
}
}
public void turnOn() {
on = true;
}
public void turnOff() {
on = false;
}
public void channelUp() {
if (on && channel < 120)
channel++;
}
// ************************************************************
public int getChannel() {
return this.channel;
}
public void setChannel(int channel) {
if (on && channel >= 1 && channel <= 120)
this.channel = channel;
else
System.err.println("Set Channel Value Bad: " + channel);
}
public int getVolumeLevel() {
return this.volumeLevel;
}
public void setVolumeLevel(int volumeLevel) {
if (on && volumeLevel >= 0 && volumeLevel <= 10)
this.volumeLevel = volumeLevel;
else
System.err.println("Set Volume Value Bad: " + volumeLevel);
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public String getId() {
return this.id;
}
public void setId(String id) {
String tmp = id.trim();
if (tmp.length() > 0)
this.id = tmp;
else
System.err.println("Bad ID");
}
// *****************************************************************
public void channelDown() {
if (on && channel > 1)
channel--;
}
public void volumeUp() {
if (on && volumeLevel < 7)
volumeLevel++;
}
public void volumeDown() {
if (on && volumeLevel > 1)
volumeLevel--;
}
@Override
public String toString() {
return "TV [id=" + id + ", channel=" + channel + ", volumeLevel=" + volumeLevel + ", on=" + on + "]";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.