Я хочу иметь возможность "включать" игровую приставку, но только если для телевизионного канала установлено значение 3. Как это сделать? - PullRequest
1 голос
/ 31 января 2020

Не обращайте внимания на другие части моего ужасного кода, все еще учитесь. Я просто пытаюсь с помощью моего класса "Console" создать метод для "playGame", но только если для "канала" класса "TV" установлено значение 3.

Моя программа говорит, что это не так есть ошибки, но когда я запускаю свою программу и устанавливаю канал на 3, я все равно не могу играть в игру. Я продолжаю получать сообщение «Вам нужно изменить канал на 3, прежде чем вы сможете играть».

Вот мои уроки:

Консоль. java

    public class Console {

        TV tv = new TV(5,25);

        private boolean isOn;
        private String reset;

        public Console(boolean isOn, String reset) {
            super();
            this.isOn = isOn;
            this.reset = reset;
        }

        public void powerButton() {
            if (isOn) {
                System.out.println("You turned off your video game console.");
                isOn = false;
            } else {
                System.out.println("You turned on your video game console.");
                isOn = true;
            }

        }

        public void reset () {
            System.out.println("You reset your game console.");
        }

        public void playGame() {
            if (tv.getChannel() == 3) {
                System.out.println("You play a game on your console.");
            } else {
                System.out.println("You need to change the channel to 3 before you can play.");
            }

        }

        public boolean isOn() {
            return isOn;
        }
        public String getReset() {
            return reset;
        }
    }

ТВ. java

    public class TV {
        private int channel = 10;
        private int volume = 25;
        public TV(int channel, int volume) {
            super();
            this.channel = channel;
            this.volume = volume;
        }

        public void channelUp () {
            channel++;
            System.out.println("The channel is now on channel " + channel);
        }

        public void channelDown () {
            channel--;
            if (channel < 0) {
                channel = 0;
            }
            System.out.println("The channel is now on channel " + channel);
        }

        public void volumeUp () {
            volume++;
            System.out.println("You changed the volume to " + volume);
        }

        public void volumeDown () {
            volume--;
            if (volume < 0) {
                volume = 0;
            }
            if (volume > 100) {
                volume = 100;
            }
            System.out.println("You changed the volume to " + volume);
        }

        public void currentChannel() {
            int currentChannel = channel;
            System.out.println("The current channel is " + channel);
        }

        public void changeChannel(int changeToChannel) {
            channel = changeToChannel;
            System.out.println("You changed the channel to " + channel);
        }

        public int getChannel() {
            return channel;
        }
        public int getVolume() {
            return volume;
        }
    }

РЕДАКТИРОВАТЬ (добавление основного класса и вывода)

Main. java

public class Main {

    public static void main (String[] args) {
//GameRoom
        Light light = new Light ("Modern");
        Macbook macbook = new Macbook ("2013", "Aluminum");
        TV tv = new TV (25,50);
        Bed bed = new Bed ("Double",3,2);
        Console console = new Console (false, "reset");

        light.turnOn();
        light.getStyle();
        light.turnOff();

        macbook.macbookDetails();

        tv.channelDown();
        tv.channelDown();
        tv.channelDown();
        tv.volumeUp();
        tv.volumeUp();

        bed.make();
        bed.messUp();
        macbook.playGame();
        macbook.turnOn();
        macbook.playGame();
        macbook.turnOff();

        console.powerButton();
        tv.currentChannel();
        tv.changeChannel(5);
        console.playGame();
        tv.changeChannel(3);
        console.playGame();
    }
}

Выход

You turned on the light in the GameRoom
Modern style lamp.
You turned off the light in the GameRoom
--Macbook details--
Year: 2013
Color: Aluminum
The channel is now on channel 24
The channel is now on channel 23
The channel is now on channel 22
You changed the volume to 51
You changed the volume to 52
You made your bed.
You messed up your bed.
You need to turn on your Macbook first.
Macbook turned on.
You played Celeste on your Macbook.
Macbook turned off.
You turned on your video game console.
The current channel is 22
You changed the channel to 5
You need to change the channel to 3 before you can play.
You changed the channel to 3
You need to change the channel to 3 before you can play.

1 Ответ

0 голосов
/ 31 января 2020

Это происходит потому, что есть два разных экземпляра телевизионного класса.

Один в консоли

public class Console {

    TV tv = new TV(5,25);

и один в точке входа

public static void main (String[] args) {
    //GameRoom
    Light light = new Light ("Modern");
    Macbook macbook = new Macbook ("2013", "Aluminum");
    TV tv = new TV (25,50);

Так что, когда вы ссылаетесь на tv.changeChannel (3) в точке входа, это экземпляр TV отличается от того, когда вы обращаетесь к tv.getChannel () в консоли.

Чтобы исправить это, вам нужно передать ссылку на экземпляр TV, созданный в точке входа, на консоль.

Я бы создал метод установки, который передает объект TV на консоль, а затем вызвал бы метод из точки входа.

//Console
public void setTV(TV tv) {
    this.tv = tv;
}

//Main
console.setTV(tv);
...