I'm Making a game which uses a parent to run an attack class as shown below
public String attack(int damage, int extradamage, String type) {
int hitpossibility;
hitpossibility = (int) ((Math.random() * 100) + 1);
if (type.compareTo("Ranged") == 0) {
weaponnoise = "twang!";
}else{
weaponnoise = "swing!";
}
if (chancetohit >= hitpossibility) {
for (int x = 0; x < damage; x++) {
result = result + (int) ((Math.random() * 6) + 1);
}
result = result + extradamage;
return weaponnoise + " The " + name + " did " + +result + " damage";
}
return weaponnoise +"The " +name+" missed!";
}
I have multiple different weapons which i want to use and have succeded in this however i have a dagger which i would like to attack twice per turn instead of once like the others. This is the class which i use to set the daggers damage values:
public class Dagger extends Blade {
public Dagger() {
super();
damage = 1;
extradamage = -1;
chancetohit = 75;
}
public String attack(int damage, int extradamage, String type) {
return super.attack(damage, extradamage, type);
}
I then have a class that runs it and currently it does this:
for (int l = 0; l < 2; l++) {
System.out.println(pointy.attack(pointy.damage, pointy.extradamage, pointy.getType()));
monsterhealth = monsterhealth - pointy.result;
System.out.println(monsterhealth);
pointy.result = 0;
}
Instead of it printing the attack twice, i want it to attack twice on the same line. I was wondering what i can change in the dagger class which would allow me to do so.
Any help is of course appreciated thank you!
This answer is an explanation of #Arnav 's comments. Here Dagger is a sub-class of the main weapon class and you want to invoke super-class' attack twice when the attack method of Dagger is called.
For this you need to call super.attack twice from Dagger attack method:
public class Dagger extends Blade {
public Dagger() {
super();
damage = 1;
extradamage = -1;
chancetohit = 75;
}
public String attack(int damage, int extradamage, String type) {
String result1 = super.attack(damage, extradamage, type);
String result2 =super.attack(damage, extradamage, type);
return // You can return result1 or result2 based on your requirement
}
Note: I deleted my earlier answer, because this approach is better than the other one.
Related
I am working on a boat program that has a super class (Boat) and two subclasses (SailBoat, Powerboat) and I must print out all of the boats information and price as well as the most expensive boat and it's information alone. This is the part I am having trouble with since I am not entirely sure how to go about it. Here is what I have so far...
Boat Class:
public class Boat {
String color;
int length;
public Boat() {
color = "white";
length = 20;
}
public Boat(String col, int leng) {
color = col;
length = leng;
}
public boolean setColor(String col) {
if ("white".equals(col) || "red".equals(col) || "blue".equals(col) || "yellow".equals(col)) {
col = color;
return true;
} else {
System.out.println("Error: can only be white, red, blue or yellow");
return false;
}
}
public String getColor() {
return color;
}
public boolean setLength(int leng) {
if (leng < 20 || leng > 50) {
leng = length;
System.out.println("Sail Boats can only be between 20 and 50 feet, inclusively.");
return false;
} else {
return true;
}
}
public int getLength() {
return length;
}
public String toString() {
String string;
string = String.format("Color = " + color + " Length = " + length);
return string;
}
public int calcPrice() {
int price;
price = 5000 + length;
return price;
}
}
PowerBoat Subclass
import java.text.NumberFormat;
public class PowerBoat extends Boat {
int engineSize;
public PowerBoat() {
super();
engineSize = 5;
}
public PowerBoat(String col, int len, int esize) {
this.color = col;
this.length = len;
engineSize = esize;
}
public boolean setEngineSize(int esize) {
if (esize < 5 || esize > 350) {
System.out.println(
"Error: That engine is too powerful. The engine size must be between 1 and 350, inclusively");
esize = engineSize;
return false;
} else {
return true;
}
}
public int calcPrice() {
int price;
price = 5000 + length * 300 + engineSize * 20;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + " Engine Size = " + engineSize + " Price = " + nf.format(calcPrice());
}
}
SailBoat subclass
import java.text.NumberFormat;
public class SailBoat extends Boat {
int numSails;
public SailBoat() {
numSails = 0;
}
public SailBoat(String col, int leng, int numsail) {
color = col;
length = leng;
numSails = numsail;
}
public boolean setNumSails(int nsails) {
if (nsails < 1 || nsails > 4) {
nsails = numSails;
return false;
} else {
return true;
}
} // end setNumSails
public int getNumSails() {
return numSails;
}
public int calcPrice() {
int price;
price = length * 1000 + numSails * 2000;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
}
public int getTotalCost() {
int totalCost = 0;
totalCost += calcPrice();
return totalCost;
}
}
Inventory class (tester)
import java.util.ArrayList;
public class Inventory {
public static void main(String[] args) {
// boat objects
Boat pb1 = new PowerBoat("blue", 22, 60);
Boat sb1 = new SailBoat("white", 20, 1);
Boat sb2 = new SailBoat("red", 42, 3);
Boat pb2 = new PowerBoat("yellow", 35, 80);
Boat pb3 = new PowerBoat("red", 50, 120);
Boat sb3 = new SailBoat("blue", 33, 2);
Boat pb4 = new PowerBoat("white", 20, 10);
ArrayList<Boat> AL = new ArrayList<Boat>();
// add boat objects to arraylist
AL.add(pb1);
AL.add(sb1);
AL.add(sb2);
AL.add(pb2);
AL.add(pb3);
AL.add(sb3);
AL.add(pb4);
// print all boat objects
System.out.println("Print all boats");
for (Boat anyBoat : AL) {
System.out.println(anyBoat.toString());
}
int max = 0;
int totalcost = 0;
Boat mostExpensiveBoat = null;
for (Boat anyBoat : AL) {
if (anyBoat instanceof SailBoat) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
}
}
}
I am really confused on how to finish up this program, the results I am supposed to get after all the boat information is printed is this..
Total price of all boats is $ 170,500.00
Most Expensive Boat: Color = red Length = 42 Number Sails = 3 Cost = $ 48,000.00
Any help will be greatly appreciated. Thank you.
There are a few design flaws you should correct:
Your Boat class should be an interface or abstract. You can't have a boat that isn't a power boat or sail boat so you should not be able to instantiate one.
Your instance variables should be private.
Make methods abstract that need to be defined by subclasses of Boat (e.g. calcPrice).
If you are able to use Java 8 then there's a nice way of getting the most expensive boat. The following code will print the most expensive boat (using Boat.toString) if one is present.
allBoats.stream()
.max(Comparator.comparingInt(Boat::calcPrince))
.ifPresent(System.out::println);
That avoids having to write the code that manually iterates through your list comparing prices. It also copes with the situation of an empty list (which means there is no maximum). Otherwise you need to initialise to null and compare to null before printing.
Your for loop should look like this:
for (Boat anyBoat : AL) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
It doesn't matter if it's a sailBoat or not, you just wanna print the information of the most expensive one, so you can remove the instanceof condition. After that:
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println("Total price of all boats is " + nf.format(totalcost));
System.out.println("Most expensive boat: " + mostExpensiveBoat.toString());
Should work, since you have already overriden the toString() methods.
one more thing: In your SailBoat toString() method, you are doing:
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
When you call the super.toString() you are printing the color and the length twice; just call
return super.toString() + " Number Sails = " + numSails + " Cost = " + nf.format(calcPrice());
So I did search and read abut every factorial listing on this site but I cannot seem to figure out what is wrong with my code. Iv tried multiple different return methods but they all keep failing. Any ideas?
public class RecursivelyPrintFactorial {
public static void printFactorial(int factCounter, int factValue) {
int nextCounter = 0;
int nextValue = 0;
if (factCounter == 0) // Base case: 0! = 1
System.out.println("1");
}
else if (factCounter == 1) // Base case: print 1 and result
System.out.println(factCounter + " = " + factValue);
}
else { // Recursive case
System.out.print(factCounter + " * ");
nextCounter = factCounter - 1;
nextValue = nextCounter * factValue;
}
return factValue * printFactorial(factValue - factCounter);
}
}
public static void main (String [] args) {
int userVal = 0;
userVal = 5;
System.out.print(userVal + "! = ");
printFactorial(userVal, userVal);
}
}
I have a feeling I have the equation incorrect in my return but iv tried every combination I can think of. Its driving me insane. Every one reports an error. Any ideas?
return factValue * printFactorial(factValue - factCounter);
I assume that you should be using the "next" values instead of these.
Edit: Also note that the function takes two parameters and is void. Returning factValue times void doesn't make sense.
Is it possible to convert the function go into the non-recursive function? Some hints or a start-up sketch would be very helpful
public static TSPSolution solve(CostMatrix _cm, TSPPoint start, TSPPoint[] points, long seed) {
TSPSolution sol = TSPSolution.randomSolution(start, points, seed, _cm);
double t = initialTemperature(sol, 1000);
int frozen = 0;
System.out.println("-- Simulated annealing started with initial temperature " + t + " --");
return go(_cm, sol, t, frozen);
}
private static TSPSolution go(CostMatrix _cm, TSPSolution solution, double t, int frozen) {
if (frozen >= 3) {
return solution;
}
i++;
TSPSolution bestSol = solution;
System.out.println(i + ": " + solution.fitness() + " " + solution.time() + " "
+ solution.penalty() + " " + t);
ArrayList<TSPSolution> nHood = solution.nHood();
int attempts = 0;
int accepted = 0;
while (!(attempts == 2 * nHood.size() || accepted == nHood.size()) && attempts < 500) {
TSPSolution sol = nHood.get(rand.nextInt(nHood.size()));
attempts++;
double deltaF = sol.fitness() - bestSol.fitness();
if (deltaF < 0 || Math.exp(-deltaF / t) > Math.random()) {
accepted++;
bestSol = sol;
nHood = sol.nHood();
}
}
frozen = accepted == 0 ? frozen + 1 : 0;
double newT = coolingSchedule(t);
return go(_cm, bestSol, newT, frozen);
}
This is an easy one, because it is tail-recursive: there is no code between the recursive call & what the function returns. Thus, you can wrap the body of go in a loop while (frozen<3), and return solution once the loop ends. And replace the recursive call with assignments to the parameters: solution=bestSol; t=newT;.
You need to thinkg about two things:
What changes on each step?
When does the algorithm end?
Ans the answer should be
bestSol (solution), newT (t), frozen (frozen)
When frozen >= 3 is true
So, the easiest way is just to enclose the whole function in something like
while (frozen < 3) {
...
...
...
frozen = accepted == 0 ? frozen + 1 : 0;
//double newT = coolingSchedule(t);
t = coolingSchedule(t);
solution = bestSol;
}
As a rule of thumb, the simplest way to make a recursive function iterative is to load the first element onto a Stack, and instead of calling the recursion, add the result to the Stack.
For instance:
public Item recursive(Item myItem)
{
if(myItem.GetExitCondition().IsMet()
{
return myItem;
}
... do stuff ...
return recursive(myItem);
}
Would become:
public Item iterative(Item myItem)
{
Stack<Item> workStack = new Stack<>();
while (!workStack.isEmpty())
{
Item workItem = workStack.pop()
if(myItem.GetExitCondition().IsMet()
{
return workItem;
}
... do stuff ...
workStack.put(workItem)
}
// No solution was found (!).
return myItem;
}
This code is untested and may (read: does) contain errors. It may not even compile, but should give you a general idea.
I am working at a project to generate a tournament using the round robin schedule algorithm. Here is the class where I implemented the algorithm:
public class Matchh {
public Team teamHome;
public Team teamAway;
public int teamHomeGoals;
public int teamAwayGoals;
public String matchDay;
public int noOfTeams;
public String[][] rounds;
public String[][] round;
Team teamList = new Team();
// no-arg constructor
Matchh() {
}
Matchh(String matchDay, Team teamHome, Team teamAway, int teamHomeGoals, int teamAwayGoals) {
this.matchDay = matchDay;
this.teamHome = teamHome;
this.teamAway = teamAway;
this.teamHomeGoals = teamHomeGoals;
this.teamAwayGoals = teamAwayGoals;
}
// round robin schedule method
public String[][] schedule() {
this.rounds = new String[(teamList.getSize() - 1) * 2][(teamList.getSize() / 2)];
for (int round = 0; round < (teamList.getSize() - 1) * 2; round++) {
for (int match = 0; match < (teamList.getSize() / 2); match++) {
this.teamHome = teamList.getIndex((round + match) % (teamList.getSize() - 1));
this.teamAway = teamList.getIndex((teamList.getSize() - 1 - match + round) % (teamList.getSize() - 1));
// Last team stays in the same place while the others rotate around it.
if (match == 0) {
teamAway = teamList.getIndex(teamList.getSize() - 1);
}
// from rounds half interchange the position of teams in rounds, to get both home and away matches
String mixedRounds;
if (round < (teamList.getSize() - 1)) {
mixedRounds = (teamHome + " vs " + teamAway + " " + teamHome.getGoal() + " - " + teamAway.getGoal());
} else {
mixedRounds = (teamAway + " vs " + teamHome + " " + teamAway.getGoal() + " - " + teamHome.getGoal());
}
rounds[round][match] = mixedRounds;
}
}
return rounds;
}
}
The schedule() method is working fine for displaying a tournament schedule for my Team teamlist, which is an Arraylist containing 12 strings (12 team names), bellow is the Team class for a better understanding. But given the way the above class is defined, I don't have the posibility to call the different properties in another class - for example if I want the total number of goals for a specific team, I would like to call a method like getTeamHomeGoals().
What I've been trying to do is to "break" the schedule() method into pieces: to define setTeamHome() and setTeamAway() methods, generate random goals for each, create a getMatchDay() method and built each round as a Matchh object containing teamHome, teamAway, teamHomeGoals, teamAwayGoals, matchDay.
so far I have the following methods (which are not returning what I intended to):
//get match day, matches ar held each week Wednesday and Sunday - we start with a Wednesday
public String getMatchDay() {
for (int round = 0; round < (teamList.getSize() - 1) * 2; round++) {
if (round % 2 == 0) {
this.matchDay = ("Wednesday" + (round + 2) / 2);
} else {
this.matchDay = ("Sunday" + (round + 1) / 2);
}
}
return matchDay;
}
//teamHome
public Team getTeamHome() {
for (int round = 0; round < (teamList.getSize() - 1) * 2; round++) {
for (int match = 0; match < (teamList.getSize() / 2); match++) {
this.teamHome = teamList.getIndex((round + match) % (teamList.getSize() - 1));
}
}
return teamHome;
}
Please give me some advices on how I should structure my Matchh class to obtain what I want, which is to link together the different properties of a match and maybe how to "break" the schedule() method.
Here is also Team class, I mentioned above
//team class
import java.util.ArrayList;
import java.util.Random;
public class Team {
// the name of the team object
private String name;
public ArrayList<Team> teamList;
//no-arg constructor, creates the array list of default teams
Team() {
this.teamList = new ArrayList<Team>();
teamList.add(new Team("Brondby IF"));
teamList.add(new Team("AaB"));
teamList.add(new Team("Viborg FF"));
teamList.add(new Team("Esbjerg"));
teamList.add(new Team("FC Copenhagen"));
teamList.add(new Team("Randers FC"));
teamList.add(new Team("FC Midtjylland"));
teamList.add(new Team("FC Nordsjaelland"));
teamList.add(new Team("Odense BK"));
teamList.add(new Team("AGF Aarhus"));
teamList.add(new Team("FC Vestsjaelland"));
teamList.add(new Team("Sonderjyske"));
}
//constructor using name
Team(String name) {
this.name = name;
}
//get name of team
public String getName() {
return name;
}
//get the size of the arrayList
public int getSize() {
return teamList.size();
}
//get an element at a specific index i
public Team getIndex(int i) {
return teamList.get(i);
}
}
Teams class:
public class Teams {
// the name of the team object
private String teamName;
Teams (String name){
this.teamName =name;
}
public String getName(){
return teamName;
}
#Override
public String toString(){
return teamName;
}
}
Game class:
public class Game {
public Teams teamHome;
public Teams teamAway;
public String day;
Game(){
}
Scheduler class (ScheduleGenerator)
public class Scheduler {
public String[][] rounds;
// round robin schedule method
public String[][] schedule(ArrayList<Teams> list){
this.rounds = new String[(list.size()-1)*2][(list.size() / 2)];
for (int round = 0; round < (list.size()-1)*2; round++) {
for (int match = 0; match < (list.size() / 2); match++) {
Game game = new Game();
game.teamHome = list.get((round + match) % (list.size() - 1));
game.teamAway = list.get((list.size() - 1 - match + round) % (list.size() - 1));
// Last team stays in the same place while the others rotate around it.
if (match == 0) {
game.teamAway = list.get(list.size() - 1);
}
// from rounds half interchange the position of teams in rounds, to get both home and away matches
String mixedRounds;
if (round < (list.size() - 1)) {
mixedRounds = ( game.teamHome + " vs " + game.teamAway );
} else
//interchange the place of teams from half ((teamList.size() - 1)
{
mixedRounds = (game.teamAway + " vs " + game.teamHome);
}
rounds[round][match] = mixedRounds;
}
}
return rounds;
}
}
and Championship class, tying all together and displaying:
import java.util.ArrayList;
import java.util.Arrays;
public class Championship {
public static ArrayList<Teams> teamList = new ArrayList<Teams>();
public static Scheduler schedule = new Scheduler();
Championship(){
}
//static ArrayList<Teams> teamList = new ArrayList<Teams>();
public void createDefaultList(int noOfTeams){
for(int i=0;i<noOfTeams;i++)
{
Championship.teamList.add(new Teams("Team "+ (i+1)));
}
}
public void createDanishLeagueList(){
teamList.add(new Teams("Brondby IF"));
teamList.add(new Teams("AaB"));
teamList.add(new Teams("Viborg FF"));
teamList.add(new Teams("Esbjerg"));
teamList.add(new Teams("FC Copenhagen"));
teamList.add(new Teams("Randers FC"));
teamList.add(new Teams("FC Midtjylland"));
teamList.add(new Teams("FC Nordsjaelland"));
teamList.add(new Teams("Odense BK"));
teamList.add(new Teams("AGF Aarhus"));
teamList.add(new Teams("FC Vestsjaelland"));
teamList.add(new Teams("Sonderjyske"));
}
public static void main(String[] args) {
Championship championship = new Championship();
//default teams (team1, team2, etc)
championship.createDefaultList(4);
//danish league teams
//championship.createDanishLeagueList();
String[][] fixtures = schedule.schedule(teamList);
// Display the schedule
for (int i = 0; i < (teamList.size() - 1)*2; i++) {
if (i%2 == 0){
System.out.println("Wednesday " + (i + 2)/2);
}
else {
System.out.println("Sunday " + (i+1)/2);
}
for (int j = 0; j < (teamList.size()/2); j++){
System.out.println(Arrays.asList(fixtures[i][j]));
System.out.println();
}
}
}
}
Put your logic in another class like ScheduleGenerator that will output a Schedule. A Schedule is a class that contains a list of matches. A match is a composition of homeTeam, visitorTeam and a date. You can also add fields for scoring and match statistics. homeTeam and visitorTeam are instance of Team class as you did. A Team only has a name in your case, but could have a list of players in the team and other properties like the city the team is from. ScheduleGenerator class will all do the logic in a static function that will create all instances of matches, giving a list of team as params.
I feel that if I give you more infos, I will be doing your homework.
I am trying to make a calculator that performs the quadratic formula.
Currently if my result would be a decimal it returns NaN. (EDIT: Resolved)
Preferably I would like the result to be in an simplified radical form (i.e. √(99) = 3√(11) ).
How would I go about achieving this?
This is what I have so far.
// Do the math
private double mathCalcPlus(double varA,double varB,double varC) {
return ((-varB + Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
private double mathCalcMinus(double varA,double varB,double varC) {
return ((-varB - Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
Any help will be greatly appreciated.
This works great! However, I decided to add the top bar of the radical sign just for fun :D
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println(" ______");
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println(" ______");
System.out.println(" " + (int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println(" ______");
System.out.println("Cannot simplify -/" + x);
}
}
}
Here's something that might help as far as simplifying radicals go. Give it the unsimplified radical (let's say 850) and it should return the correct answer (5-/34). It also tries to recursively simplify what's left in the radical in case it needs to be broken down again.
This was written quickly so I'm sure there are edge cases I missed that will throw off the calculations but I hope it helps at least a little. Best of luck!
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println((int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println("Cannot simplify -/" + x);
}
}
}