剧院的舞台上安装了聚光灯。每个聚光灯都可以打开,关闭或变暗。写一个名为Spotlight的类来表示聚光灯。该类应具有一个字段变量status,以存储聚光灯的状态(开,关或变暗)。除了构造函数之外,您的类还应包含以下方法:
如果聚光灯关闭,
- 如果聚光灯亮起,
isOff()
将返回true,否则返回false- 如果聚光灯变暗,则
isOn()
将返回true,否则返回falseisDimmed()
返回true,否则返回falseon()
让人们关注off()
关闭聚光灯dim()
使聚光灯变暗- 醇>
toString
将有关聚光灯的信息作为字符串返回。
所以这是我的班级,到目前为止我所拥有的:
class Spotlight
{
private String status; //the status of the spotlight
//constructor
public Spotlight(String s)
{
status = s;
}
//get the spotlights status
public String getStatus()
{
return status;
}
//set the spotlights status
public void setStatus(String newS)
{
status = newS;
}
//method to show that the spotlight is off
public boolean isOff()
{
if (status.equalsIgnoreCase("Off"))
{
return true;
}
else
{
return false;
}
}
//method to show that the spotlight is on
public boolean isOn()
{
if (status.equalsIgnoreCase("On"))
{
return true;
}
else
{
return false;
}
}
//method to show that the spotlight is dimmed
public boolean isDimmed()
{
return false;
}
//method to show that the spotlight is off
public boolean on()
{
if (status.equalsIgnoreCase("On"))
{
return true;
}
else
{
return false;
}
}
//method to show that the spotlight is off
public boolean off()
{
if (status.equalsIgnoreCase("Off"))
{
return true;
}
else
{
return false;
}
}
//method to show that the spotlight is off
public boolean dim()
{
return false;
}
//return all the information about the employee as a String
public String toString()
{
return "Status: " + this.getStatus();
}
}
Spotlight a = new Spotlight("Off");
Spotlight b = new Spotlight("Off");
Spotlight c = new Spotlight("Off");
Spotlight d = new Spotlight("Off");
Spotlight e = new Spotlight("Off");
//print out the information about them
System.out.println();
System.out.println(a.toString());
System.out.println();
System.out.println(b.toString());
System.out.println();
System.out.println(c.toString());
System.out.println();
System.out.println(d.toString());
System.out.println();
System.out.println(e.toString());
System.out.println();
System.out.println("Select a light to turn on a-e");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Spotlight f = new Spotlight(input);
到目前为止,我可以更改聚光灯的状态并让它显示我的结果,但如果我使用的是二十个聚光灯对象,我该如何选择要打开的灯?
答案 0 :(得分:1)
简单方法:
List<SpotLight> spotlights = new ArrayList<>();
for(int i = 0; i < 20; i++)
spotlights.add(new SpotLight("Off"));
int choice = 0;
do {
System.out.println("Select a light to turn on 1-20");
choice = sc.nextInt();
} while(choice < 1 || choice > 20);
spotlights.get(choice - 1).on();
System.out.println(spotlights);
作为旁注,您应该让您的聚光灯课程使用enum
代替这些字符串:
public class SpotLight {
public enum State {
On,
Off,
Dimmed
}
private State state;
public SpotLight(State state) {
this.state = state;
}
...
}
然后,例如,创建一个聚光灯:
SpotLight spotlight = new SpotLight(SpotLight.State.Off);