Мои операторы if портят мое меню? - PullRequest
0 голосов
/ 30 октября 2019

Я создал игру о рыбалке с меню. Пользователь просто вводит письмо, чтобы сделать эту опцию. Однако, когда я пытаюсь получить доступ к коду в соответствующем операторе if, по какой-то причине он либо пропускает его, либо отображает статистику рекордов. Я попытался изменить буквы, чтобы понять, не сработала ли эта проблема. Может быть, это то, как я сравниваю строку ввода пользователя (я использую .equals) или, может быть, это большая проблема, которую я не вижу. Короче говоря, мои операторы if не работают как меню, а некоторые операторы if, такие как my r для 'ready up' для рыбалки, ничего не делают. Или вы можете «купить обновления» для удочки.

//Intense Fishing Simulator 2019
//2019-10-29
//Ormim Bari
//to practice the usage of realtionships.
package com.mycompany.intensefishingsimulator2019_ormimbari;

 import java.io.*;

public class DriverClass 
{
    public static void main (String args[]) throws IOException
    {
        BufferedReader MyInput=new BufferedReader (new InputStreamReader(System.in));

        Fisher joe = new Fisher(); //creates the fisher

        System.out.println("Welcome to Intesne Fishing Simulator 2019");
        System.out.println("You join fisher Joe's in the intense world of Fishing");
        int money=0;
        int endGame=0;
        boolean purchase1=false;//if purchased firsst upgrade
        boolean purchase2=false;//if purchased last upgrade
        do
        {
            //menu
            System.out.println("Enter r when ready to catch a fish");
            System.out.println("Enter c to see total of cash earned");
            System.out.println("Enter f to see total amount of fish caught");
            System.out.println("Enter u to upgrade your fishing rod");
            System.out.println("Enter joe to see stats");
            System.out.println("Enter Exit to end game ");

            String strInput=MyInput.readLine(); //gathers ihnput

            //ends game
            if (strInput.equals("Exit"))
            {
                endGame=999;
            }
            //display hp and fishing rod damage
            if (strInput.equals("joe"))
            {
                strInput="";
                System.out.println("Joe has a total hp of " +joe.getHp());
                System.out.println("Joes fishingrod does a total of "+joe.fr.getDamage() +" damage");

            }
            //display career total of fish caught
            if (strInput.equals("f"));
            {
                strInput="";
                System.out.println("You caught a total of"+joe.GetCatches()+"fishes");

            }
            //display career total of cash earned
            if (strInput.equals("c"));
            {
                strInput="";
                System.out.println( "You earned a total of $"+joe.getCashTotal());

            }
            if (strInput.equals("u"))
            {

                if (purchase1==false)
                {
                    System.out.println("Welcome to the shop! The first upgrade is $30. To buy enter b");
                    strInput=MyInput.readLine();
                    if (strInput.equals("b"))
                    {
                        strInput="";
                       boolean sucess= joe.fr.Upgrade1(money, joe, joe.fr);
                       if (sucess==true)
                       {
                           purchase1=true;
                       }
                    }
                }
                if (purchase1==true)
                {
                    System.out.println("Welcome to the shop! The last upgrade is $50. To buy enter b");
                    strInput=MyInput.readLine();
                    if (strInput.equals("b"))
                    {
                        strInput="";
                       boolean sucess= joe.fr.Upgrade2(money, joe, joe.fr);
                       if (sucess==true)
                       {
                           purchase2=true;
                       }
                    }
                }
                if (purchase2==true)
                {
                    System.out.println("You purchased all the upgrades");
                }
            }
            //user chooses to 'ready up' to fish
            if (strInput.equals("r"))
            {
                strInput="";
                int endFishing=0;

                //creation of fish to fight
                Fish fish= new Fish();

                //ceratopm of all fish 
                TunaFish tf= new TunaFish(); 
                SilverCarp sc= new SilverCarp();    
                Shark shark= new Shark();

                //intro
                System.out.println("You have been approached by a " + fish.getType());
                do
                {
                    //instructions
                    System.out.println("Enter a to attack the fish or r to run away");
                    strInput=MyInput.readLine(); 
                    //if chosing to run away
                    if (strInput.equals("r"))
                    {
                        strInput="";
                        boolean sucess;
                        sucess=joe.RunAway();
                        //if sucesfull
                        if (sucess==true)
                        {
                            joe.RunAwaySucess(joe);
                            endFishing=999;
                        }
                        //if joe failed to runaway
                        if (sucess==false)
                        {
                            //if tuna
                            if (fish.getType().equals("Tuna Fish"))
                            {   

                                boolean damageGiven= tf.AttackChanceTuna();
                                //if tuna dosnt miss
                                if (damageGiven==true)
                                {
                                    //joe gets the damage 
                                    joe.HarmJoe(tf.returnTunaDamage());
                                    System.out.println("Joe has been harmed by the tuna for "+ tf.returnTunaDamage());
                                    System.out.println("Joe now has" + joe.getHp());

                                    //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999; //ends game
                                    }
                                }
                            }

                            //if carp
                            if (fish.getType().equals("Silver Carp"))
                            {
                                boolean damageGiven= sc.AttackChanceCarp();
                                //if carp dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(sc.returnCarpDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ sc.returnCarpDamage());
                                    System.out.println("Joe now has" + joe.getHp());
                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999; //ends game
                                    }
                            }
                            //if shark
                            if (fish.getType().equals("Shark"))
                            {
                                boolean damageGiven= shark.AttackChanceShark();
                                //if shark dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(shark.returnSharkDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ shark.returnSharkDamage());
                                    System.out.println("Joe now has" + joe.getHp());


                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999; //ends game
                                    }
                            }

                        }

                    }
                    //if attacking
                    if (strInput.equals("a"))
                    {
                        strInput="";
                        //tells user it did attack
                        fish.HarmFish(joe.fr.getDamage());
                        System.out.println("Joe has hurt " + fish.getType()+ "for "+ joe.fr.getDamage()+"damage");

                         //if tuna
                            if (fish.getType().equals("Tuna Fish"))
                            {
                                //damage the tuna
                                tf.harmTuna(joe.fr.getDamage());

                                boolean damageGiven= tf.AttackChanceTuna();
                                //if tuna attacks
                                if (damageGiven==true)
                                {
                                    //joe gets the damage if true
                                    joe.HarmJoe(tf.returnTunaDamage());
                                    System.out.println("Joe has been harmed by the tuna for "+ tf.returnTunaDamage());
                                    System.out.println("Joe now has" + joe.getHp());

                                    //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999;
                                    }
                                    //if tuna dies
                                    if (tf.getTunaHp()<=0)
                                    {
                                        //reward screen output
                                        System.out.println("You beat the tuna!You got " + tf.fl.getLootType());
                                        System.out.println("You sold the " + tf.fl.getLootType()+ "for $" + tf.fl.getLootPrice());
                                        joe.increaseCash(tf.fl.getLootPrice());
                                        System.out.println("You now have $" + joe.getMoney()); //cash update
                                        tf.healTuna();//reset for next potential round
                                        joe.CareerCashTotal(tf.fl.getLootPrice()); //add to highscore
                                        joe.addCatches(); // add to high score
                                        endFishing=999; //stops the fishing
                                    }
                                }
                            }

                            //if carp
                            if (fish.getType().equals("Silver Carp"))
                            {
                                //damages the tuna
                                sc.harmCarp(joe.fr.getDamage());
                                boolean damageGiven= sc.AttackChanceCarp();
                                //if tuna dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(sc.returnCarpDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ sc.returnCarpDamage());
                                    System.out.println("Joe now has" + joe.getHp());
                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999;
                                    }
                                    if (sc.getCarpHp()<=0)
                                    {
                                         //reward screen output
                                        System.out.println("You beat the silver carp!You got " + sc.fl.getLootType());
                                        System.out.println("You sold the " + sc.fl.getLootType()+ "for $" + sc.fl.getLootPrice());
                                        joe.increaseCash(sc.fl.getLootPrice());
                                        System.out.println("You now have $" + joe.getMoney()); //upgrade cash
                                        sc.healCarp();//reset for next potential round
                                        joe.CareerCashTotal(sc.fl.getLootPrice()); //add to high score
                                        joe.addCatches(); //add to high score
                                        endFishing=999; //stops the fishing
                                    }
                            }
                            //if shark
                            if (fish.getType().equals("Shark"))
                            { 
                                //harms the shark
                                shark.harmShark(joe.fr.getDamage());
                                boolean damageGiven= shark.AttackChanceShark();
                                //if shark dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(shark.returnSharkDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ shark.returnSharkDamage());
                                    System.out.println("Joe now has" + joe.getHp());


                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999;
                                    }
                                //if shark dies
                                if (shark.getSharkHp()<=0)
                                    {
                                        //reward screen output
                                        System.out.println("You beat the Shark!You got " + shark.fl.getLootType());
                                        System.out.println("You sold the " + shark.fl.getLootType()+ "for $" + shark.fl.getLootPrice());
                                        joe.increaseCash(shark.fl.getLootPrice());
                                        System.out.println("You now have $" + joe.getMoney()); //updatees cash
                                        shark.healShark();//reset for next potential round
                                        joe.CareerCashTotal(shark.fl.getLootPrice()); //adds to high score
                                        joe.addCatches(); //adds to high score
                                        endFishing=999;
                                    }
                            }

                        }

                } while (endFishing!=999);
            }



        }while (endGame!=999);

        System.out.println("Thanks for joining Joe in the world of Intense Fishing ");


    }



}

Ответы [ 2 ]

1 голос
/ 06 ноября 2019

Я думаю, что размер единственного main метода мешает вашему пониманию поведения кода.

Вы даете подсказки относительно того, что код должен делать, написав комментарии вроде: //display career total of fish caught и //user chooses to 'ready up' to fish. Это неправильно.

Все эти подсказки должны быть преобразованы в методы. Например: displayFishCaught() и isReadyUpFish().

Это процедурное программирование;Вы можете захотеть изучить использование классов и объектов для перемещения кода из одного класса. Вы можете найти множество курсов и учебников по объектно-ориентированному программированию.

После рефакторинга вы увидите, что, например, когда пользователь хочет выйти из игры, весь несвязанный код все еще выполняется, защищая sea из if операторов. Это доказывает, что ваш код не обслуживается без серьезных головных болей.

Я сожалею, потому что это, вероятно, не тот ответ, который вы прыгали, чтобы получить.

0 голосов
/ 06 ноября 2019

У вас есть

if (...);
{

Таким образом, пустой оператор, когда условие истинно (;), сопровождаемый блоком { ... }, всегда вводится.

Переменная strInput является слишком глобальным и изменяется везде и может позже ввести неверный оператор if.

В одном решении используется else if:

        String strInput=MyInput.readLine(); //gathers ihnput
        if (strInput.equals("Exit"))
        {
            //ends game
            endGame=999;
        } else if (strInput.equals("joe")) {
            //display hp and fishing rod damage
            strInput="";
            System.out.println("Joe has a total hp of " +joe.getHp());
            System.out.println("Joes fishingrod does a total of "+joe.fr.getDamage() +" damage");

        } else if (strInput.equals("f")) {
            //display career total of fish caught
            strInput="";
            System.out.println("You caught a total of"+joe.GetCatches()+"fishes");
        }

Вы также можете удалить переменную:

        switch (MyInput.readLine()) { //gathers ihnput
        case "Exit":
            //ends game
            endGame=999;
            break;
        case "joe":
            //display hp and fishing rod damage
            System.out.println("Joe has a total hp of " +joe.getHp());
            System.out.println("Joes fishingrod does a total of "+joe.fr.getDamage() +" damage");
            break;
        case "f":
            //display career total of fish caught
            System.out.println("You caught a total of"+joe.GetCatches()+"fishes");
            breaK;
        default:
            System.out.println("Wrong input");
        }

Подойдет и конкретная локальная переменная.

        String menuAnswer = MyInput.readLine();
        switch (menuAnswer) {
        ...
        default:
            System.out.println("Wrong input: " + menuAnswer);
        }

Соглашения Java В отличие от других языков, польская запись strInput не используются в Java. Также переменные по соглашению начинаются с маленькой буквы. Переменные объявляются как можно ближе к первому использованию. Имена классов начинаются с заглавной буквы.

...