java定义一个电视机类,实现电视机的基本功能。
1.先定义一个电视机类和方法。
public class TV{
int tvchannel =0;
int tvvolume =0;
int tvswitch =0;
public void ChangeChannel(int tvchannel){
this.tvchannel=tvchannel;
System.out.println("现在是"+tvchannel+"台");
}
public void VolumeAdjustment(int changevolume){
if(changevolume==1){
if (tvvolume>=3){
System.out.println("已经调到最大音量!");
return;
}
this.tvvolume++;
}
else if (changevolume==0){
if (tvvolume<=0){
System.out.println("已经调整到最小的音量!");
return;
}
this.tvvolume--;
}
else
System.out.println("ERROR!");
System.out.println("现在音量是"+this.tvvolume);
}
public void Switch(int tvswitch){
if (tvswitch==1){
System.out.println("打开电视!");
}
else if (tvswitch==0){
System.out.println("关闭电视!");
}
else
System.out.println("ERROR!");
this.tvswitch=tvswitch;
}
}
2.调用类和方法。
import java.util.Scanner;
public class TV2 {
public static void main(String[] args){
TV tv=new TV();
System.out.println("电视处于关闭!");
int select=1;
Scanner in =new Scanner(System.in);
System.out.println("1.打开电视!");
System.out.println("0.离开!");
System.out.println("请选择:");
select = in.nextInt();
tv.Switch(select);
if (select==0){
System.out.println("已退出!");
return;
}
else {
while (select!=0){
System.out.println("1.换台!");
System.out.println("2.调音量");
System.out.println("0.关电视!");
System.out.println("请选择:");
select=in.nextInt();
switch (select){
case 1:
int tvchannel=0;
System.out.println("请输入台数:");
tvchannel=in.nextInt();
tv.ChangeChannel(tvchannel);
break;
case 2:
int tvvolume=0;
System.out.println("1.增大音量!");
System.out.println("0.减小音量!");
tvvolume=in.nextInt();
tv.VolumeAdjustment(tvvolume);
break;
case 0:
tv.Switch(select);
System.out.println("已退出!");
break;
}
}
}
}
}