Question

Hello, There are some elements in my code that aren't working properly that need to be...

Hello,

There are some elements in my code that aren't working properly that need to be fixed but I don't know what I have done wrong.

  1. The printHealthBars() should print out a '+' for each point of current health and a '-' for each difference between current & max health. So, for instance, suppose the pokemon had 6/8 health, the method should print: "[ ++++++-- ]"
  2. Something is up with the damage calculation method. The idea is that it should come up with some numbers between the min and max damage. So suppose a pokemon has 2-4 damage, the pokemon should deal damage between 2-4 (inclusive)

The idea of the program is that it alternates between the "player" and the monster, doing attacks and dealing damage to one another until one of them drops <=0 current hp (aka - a basic combat loop). Your goal is to fix it and make sure it all runs smoothly. There may or may not be issued outside of those listed above.

You are free to change/remove methods if you feel it will help the program work better, but remember that the end product needs to be as the goal described above. You will be graded on whether the program compiles & runs without issue, and how well you were able to iron out the kinks.

CODE:

package prelabs;

import java.util.*;

public class Ch6Prelab {
    // Pokemon stats
    public static int p1MaxHp = 10, p1CurrHp = 10, p2MaxHp = 8, p2CurrHp = 8;
    public static int p1MinDmg = 2, p1MaxDmg = 4, p2MinDmg = 1, p2MaxDmg = 3;
    public static String p1Name = "Pikachu", p2Name = "Spearow";

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int turn = 1;
        while (p1CurrHp > 0 && p2CurrHp > 0) {
            String currPlayer = p1Name;
            // What is the '%' operator called, and what does it do?
            if (turn%2 == 0) currPlayer = p2Name;

            // If I wrote these like System.out.println(printHealthBar(p1CurrHp, p1MaxHp, p1Name));
            // would that work? Why or why not.
            printHealthBar(p1CurrHp, p1MaxHp, p1Name);
            printHealthBar(p2CurrHp, p2MaxHp, p2Name);

            System.out.printf("%s's turn.\n", currPlayer.toUpperCase());

            // What does turn%2 calculate? What is the importance of it?
            if (turn%2 != 0) {
                System.out.println("Select an ability by entering 1-4.");
                printAbilities();

                int n = sc.nextInt();

                // What is happening on line 44? Include, in your comment, the flow of calls starting in main()
                // More explicitly, starting from main, what function do we go in to first? How do we get back to main?
                // ex: main() --> foo() --> bar() --> main()
                p2CurrHp = takeDmg(p2CurrHp, useAbility(p1Name, n));
            } else {
                int dmg = calculateDmg(p2MinDmg,p2MaxDmg);
                System.out.printf("%s attacks %s for %d damage!\n", p2Name.toUpperCase(), p1Name.toUpperCase(), dmg);
                p1CurrHp = takeDmg(p1CurrHp, dmg);
            }

            turn++;
        }
    }

    public static String getAbility(int n) {
        // In your block comments, rewrite this switch statement in if-else/if-else if form
        // Compare the two forms, which do you think is better?
        switch(n) {
            case 1:
                return "Scratch";
            case 2:
                return "Tackle";
            case 3:
                return "Lightning Bolt";
            case 4:
                return "Thunder";
        }

        return "???";
    }

    // What does the 'void' keyword mean?
    public static void printAbilities() {
        System.out.println("1. Scratch\t\t3. Lightning Bolt");
        System.out.println("2. Tackle\t\t4. Thunder");
    }

    public static int useAbility(String name, int n) {
        int dmg = 0;
        // In your block comments, rewrite this switch statement in if-else/if-else if form
        // Compare the two forms, which do you think is better?
        switch (n) {
            case 1:
                dmg = calculateDmg(p1MinDmg-1, p1MaxDmg-1);
                break;
            case 2:
            case 3:
            case 4:
                dmg = calculateDmg(p1MinDmg+n, p1MaxDmg+n);
                break;
            default:
                System.out.println("Your Pokemon doesn't understand your command.");
                return 0;
        }

        System.out.printf("%s used %s for %d damage!\n",name.toUpperCase(), getAbility(n).toUpperCase(), dmg);
        return dmg;
    }

    public static int calculateDmg(int min, int max) {
        int range = max-min+1;
        return (new Random().nextInt()*range) + min;
    }

    public static int takeDmg(int currHp, int dmg) {
        return currHp-dmg;
    }

     public static void printHealthBar(int currHp, int maxHp, String name) {
        System.out.println(name.toUpperCase());
        System.out.print("[ ");
        for (int i=0; i<maxHp; i++) {
            for (int j=0; j<currHp; j++) {
                System.out.print("+");
            }

            System.out.print("-");
        }

        System.out.print(" ]");
    }


}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hello Student,

I have edited the given program, now it is running properly with the given instructions, also i have added command to print the players health at the end and winner's name.

Please read the comments in the program to understand the corrections made.

CODE :


import java.util.*;

public class Ch6Prelab {
    // Pokemon stats
    public static int p1MaxHp = 10, p1CurrHp = 10, p2MaxHp = 8, p2CurrHp = 8;
    public static int p1MinDmg = 2, p1MaxDmg = 4, p2MinDmg = 1, p2MaxDmg = 3;
    public static String p1Name = "Pikachu", p2Name = "Spearow";

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);

        int turn = 1;
        while (p1CurrHp > 0 && p2CurrHp > 0) 
        {
            String currPlayer = p1Name;

            //% is modulus, it returns the remainder after dividing turn with 2.
            if (turn%2 == 0) 
                currPlayer = p2Name;

            //No, because these are function calls.
            printHealthBar(p1CurrHp, p1MaxHp, p1Name);
            printHealthBar(p2CurrHp, p2MaxHp, p2Name);

            System.out.printf("\n%s's turn.\n", currPlayer.toUpperCase());


            //it calculates the remainder to check for pikachu's turn. 
            if (turn%2 != 0) 
            {
                System.out.println("Select an ability by entering 1-4.");
                printAbilities();

                int n = sc.nextInt();

                //p2 current hp is calculated by takeDmg and useAbility function.
                p2CurrHp = takeDmg(p2CurrHp, useAbility(p1Name, n));
            } 
            else
            {
                int dmg = calculateDmg(p2MinDmg,p2MaxDmg);
                System.out.printf("\n%s attacks %s for %d damage!\n\n", p2Name.toUpperCase(), p1Name.toUpperCase(), dmg);
                p1CurrHp = takeDmg(p1CurrHp, dmg);
            }

            turn++;
        }
        //prints the hp of each player after the battle.
        printHealthBar(p1CurrHp, p1MaxHp, p1Name);
        printHealthBar(p2CurrHp, p2MaxHp, p2Name);
        if (p1CurrHp > 0)
           System.out.println("\nPIKACHU WON THE BATTLE"); 
        else
           System.out.println("\nSPEAROW WON THE BATTLE");  
    }

    public static String getAbility(int n)
    {
     //best is the switch case way
        switch(n) {
            case 1:
                return "Scratch";
            case 2:
                return "Tackle";
            case 3:
                return "Lightning Bolt";
            case 4:
                return "Thunder";
        }

        return "???";
    }
    //void here specifies for no return value.
    public static void printAbilities() 
    {
        System.out.println("1. Scratch\t\t3. Lightning Bolt");
        System.out.println("2. Tackle\t\t4. Thunder");
    }

    public static int useAbility(String name, int n) 
    {
        int dmg = 0;
    //best is the switch case.
        switch (n) 
        {
            case 1:
                dmg = calculateDmg(p1MinDmg, p1MaxDmg);
                break;
            case 2:
                dmg = calculateDmg(p1MinDmg, p1MaxDmg);
                break;
            case 3:
                dmg = calculateDmg(p1MinDmg, p1MaxDmg);
                break;
            case 4:
                dmg = calculateDmg(p1MinDmg, p1MaxDmg);
                break;
            default:
                System.out.println("\nYour Pokemon doesn't understand your command.\n");
                return 0;
        }

        System.out.printf("\n%s used %s for %d damage!\n\n",name.toUpperCase(), getAbility(n).toUpperCase(), dmg);
        return dmg;
    }

    public static int calculateDmg(int min, int max) 
    {
        //no need was to specify range.
        return new Random().nextInt(max - min + 1) + min;
    }

    public static int takeDmg(int currHp, int dmg)
    {
        return currHp-dmg;
    }

    public static void printHealthBar(int currHp, int maxHp, String name) 
     {
        System.out.println(name.toUpperCase());
        System.out.print("[ ");
        //here j for loop and i for loop should be seperate to print the hp once. 
        for (int j=0; j<currHp; j++) 
         {
             System.out.print("+");
         }
        
        for (int i=0; i<maxHp-currHp; i++) 
        {

            System.out.print("-");
        }

        System.out.print(" ]\n");
    }


}

OUTPUT:

cs. C:\Windows\system32\cmd.exe PIKACHU [ ++++++---- ] SPEAROW [ ] +------- SPEAROWs turn. SPEAROW attacks PIKACHU for 1 dam

The program is running successfully and the damage count is also random between min and max according to the player.

NOTE- there was a: package prelabs; on top of the code, its upto you to write it or not.

---------------------------------------------------------------------------------------------------------------------------------------------------------

THANK YOU!

LIKE THE ANSWER IF IT HELPED YOU

Add a comment
Know the answer?
Add Answer to:
Hello, There are some elements in my code that aren't working properly that need to be...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • Hi, So I have a finished class for the most part aside of the toFile method...

    Hi, So I have a finished class for the most part aside of the toFile method that takes a file absolute path +file name and writes to that file. I'd like to write everything that is in my run method also the toFile method. (They are the last two methods in the class). When I write to the file this is what I get. Instead of the desired That I get to my counsel. I am having trouble writing my...

  • I need to change the following code so that it results in the sample output below...

    I need to change the following code so that it results in the sample output below but also imports and utilizes the code from the GradeCalculator, MaxMin, and Student classes in the com.csc123 package. If you need to change anything in the any of the classes that's fine but there needs to be all 4 classes. I've included the sample input and what I've done so far: package lab03; import java.util.ArrayList; import java.util.Scanner; import com.csc241.*; public class Lab03 { public...

  • Step 4: Add code that discards any extra entries at the propmt that asks if you...

    Step 4: Add code that discards any extra entries at the propmt that asks if you want to enter another score. Notes from professor: For Step 4, add a loop that will validate the response for the prompt question:       "Enter another test score? (y/n): " This loop must only accept the single letters of ‘y’ or ‘n’ (upper case is okay). I suggest that you put this loop inside the loop that already determines if the program should collect...

  • (a)How many times does the code snippet given below display "Hello"? int x = 1; while...

    (a)How many times does the code snippet given below display "Hello"? int x = 1; while (x != 15) {    System.out.println ("Hello");    x++; } (b)What is the output of the following code fragment? int i = 1; int sum = 0; while (i <= 5) {    sum = sum + i;    i++; } System.out.println("The value of sum is " + sum); Quie 2 What is the output of the following snipped code? public class Test {...

  • I cant get the code to work. Any help would be appreciated. Instruction.java package simmac; public...

    I cant get the code to work. Any help would be appreciated. Instruction.java package simmac; public class Instruction { public static final int DW = 0x0000; public static final int ADD = 0x0001; public static final int SUB = 0x0002; public static final int LDA = 0x0003; public static final int LDI = 0x0004; public static final int STR = 0x0005; public static final int BRH = 0x0006; public static final int CBR = 0x0007; public static final int HLT...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • I need help with this method (public static int computer_move(int board[][])) . When I run it...

    I need help with this method (public static int computer_move(int board[][])) . When I run it and play the compute.The computer enters the 'O' in a location that the user has all ready enter it sometimes. I need to fix it where the computer enters the 'O' in a location the user has not enter the "X' already package tictactoe; import java.util.Scanner; public class TicTacToeGame { static final int EMPTY = 0; static final int NONE = 0; static final...

  • (How do I remove the STATIC ArrayList from the public class Accounts, and move it to...

    (How do I remove the STATIC ArrayList from the public class Accounts, and move it to the MAIN?) import java.util.ArrayList; import java.util.Scanner; public class Accounts { static ArrayList<String> accounts = new ArrayList<>(); static Scanner scanner = new Scanner(System.in);    public static void main(String[] args) { Scanner scanner = new Scanner(System.in);    int option = 0; do { System.out.println("0->quit\n1->add\n2->overwirte\n3->remove\n4->display"); System.out.println("Enter your option"); option = scanner.nextInt(); if (option == 0) { break; } else if (option == 1) { add(); } else...

  • public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc...

    public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc = new Scanner(System.in);         String choice = "y";         while (choice.equalsIgnoreCase("y")) {             // get the input from the user             System.out.println("DATA ENTRY");             double monthlyInvestment = getDoubleWithinRange(sc,                     "Enter monthly investment: ", 0, 1000);             double interestRate = getDoubleWithinRange(sc,                     "Enter yearly interest rate: ", 0, 30);             int years = getIntWithinRange(sc,                     "Enter number of years: ", 0, 100);             System.out.println();            ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT