How can I simplify this mathematic operation in my call to super? - java

I am attempting to do a project which models a grocery store that sells various desserts. Currently, I am trying to create a class for a tiered cake which is derived from a cake class which itself is derived from an abstract dessert class. Essentially, the cake class's constructor has two parameters, name and price. For the tiered cake, the price is the price of the base + the price of the top + an additional 10% of the total. I've found a way to do this, but it's a really long, ugly line of code. I've experimented with a few ways to try and simplify it using variables, but I can't seem to figure out a way that works with the fact that it is being done within a super(). Is there a way I could make it simpler and more efficient? Thanks in advance!
Here is the code:
public class TieredCake extends Cake {
private Cake base;
private Cake top;
public TieredCake (Cake base, Cake top) {
super(base.getName() + " with an upper tier of " + top.getName(), (base.getPrice() + top.getPrice()) * 0.10 + base.getPrice()+top.getPrice());
this.base = base;
this.top = top;
}
public Cake getBase() {
return base;
}
public Cake getTop() {
return top;
}
}

Splitting the call to super onto multiple lines helps a little:
public TieredCake(Cake base, Cake top) {
super(
base.getName() + " with an upper tier of " + top.getName(),
(base.getPrice() + top.getPrice()) * 0.10 + base.getPrice() + top.getPrice()
);
this.base = base;
this.top = top;
}
But more importantly, let’s take a look at that formula. There’s a bit of simplification we can do at a mathematical level:
B := base.getPrice()
T := top.getPrice()
(B + T) * 0.1 + B + T
= (B * 0.1) + (T * 0.1) + B + T
= (B * 1.1) + (T * 1.1)
= (B + T) * 1.1
That gives us:
public TieredCake(Cake base, Cake top) {
super(
base.getName() + " with an upper tier of " + top.getName(),
(base.getPrice() + top.getPrice()) * 1.1
);
this.base = base;
this.top = top;
}

Related

How do i make it so that my .equals() are true instead of false? especially for f98p6.equals(c37Minus)), c10.equals(c10Plus) and c0.equals(f32))

I have an assignment that i'm having a bit of trouble and i would like some help.
This is the Driver program
package a07;
/**
* A class to test the Temperature class
*
* #author Mark Young (A00000000)
*/
public class TestTemps {
// switch depending on whether output is for NetBeans or the Web
public static final String DEGREES = "\u00B0"; // NetBeans
// public static final String DEGREES = "°"; // Web
public static void main(String[] args) {
// Constructors
System.out.println("\nConstructors\n");
Temperature c0 = new Temperature(0);
Temperature c10 = new Temperature(10.0);
Temperature f32 = new Temperature(32.0, 'F');
Temperature c10Plus = new Temperature(10.03, 'C');
System.out.println("Should be an error message near here ");
Temperature c40 = new Temperature(40, 'K');
Temperature f98p6 = new Temperature(98.6, 'f');
Temperature c37Minus = new Temperature(36.97, 'c');
Temperature cMinus40 = new Temperature(-40);
Temperature fMinus40 = new Temperature(-40, 'F');
// toString
System.out.println("\ntoString\n");
System.out.println("Should be 0.0" + DEGREES + "C: " + c0);
System.out.println("Should be 10.0" + DEGREES + "C: " + c10);
System.out.println("Should be 32.0" + DEGREES + "F: " + f32);
System.out.println("Should be 10.03" + DEGREES + "C: " + c10Plus);
System.out.println("Should be 40.0" + DEGREES + "C: " + c40);
System.out.println("Should be 98.6" + DEGREES + "F: " + f98p6);
System.out.println("Should be 36.97" + DEGREES + "C: " + c37Minus);
System.out.println("Should be -40.0" + DEGREES + "C: " + cMinus40);
System.out.println("Should be -40.0" + DEGREES + "F: " + fMinus40);
// conversions
System.out.println("\nCelsius to Fahrenheit Conversion\n");
for (int c = -40; c <= 100; c += 14) {
System.out.printf("%4d" + DEGREES + "C == %5.1f" + DEGREES + "F\n",
c, Temperature.celsiusToFahrenheit(c));
}
// more conversions
System.out.println("\nFahrenheit to Celsius Conversion\n");
for (int f = -40; f <= 212; f += 28) {
System.out.printf("%4d" + DEGREES + "F == %5.1f" + DEGREES + "C\n",
f, Temperature.fahrenheitToCelsius(f));
}
// getFahrenheit
System.out.println("\ngetFahrenheit\n");
System.out.println("Should be 32.0: " + c0.getFahrenheit());
System.out.println("Should be 50.0: " + c10.getFahrenheit());
System.out.println("Should be 32.0: " + f32.getFahrenheit());
System.out.println("Should be -40.0: " + fMinus40.getFahrenheit());
// getCelsius
System.out.println("\ngetCelsius\n");
System.out.println("Should be 0.0: " + c0.getCelsius());
System.out.println("Should be 10.0: " + c10.getCelsius());
System.out.println("Should be 0.0: " + f32.getCelsius());
System.out.println("Should be -40.0: " + fMinus40.getCelsius());
// equals
System.out.println("\nequals\n");
System.out.println("Should be true: " + c0.equals(c0));
System.out.println("Should be false: " + c0.equals(c10));
System.out.println("Should be true: " + c0.equals(f32));
// fuzz
System.out.println("\nfuzz\n");
System.out.println("Should be 0.2: " + Temperature.getFuzz());
System.out.println("Should be true: " + c10.equals(c10Plus));
System.out.println("Should be true: " + f98p6.equals(c37Minus));
Temperature.setFuzz(0.01);
System.out.println("Should be 0.01: " + Temperature.getFuzz());
System.out.println("Should be false: " + c10.equals(c10Plus));
System.out.println("Should be false: " + f98p6.equals(c37Minus));
System.out.println("Should be an error message near here");
Temperature.setFuzz(-0.5);
System.out.println("Should be 0.01: " + Temperature.getFuzz());
Temperature.setFuzz(0);
System.out.println("Should be 0.0: " + Temperature.getFuzz());
System.out.println("Should be true: " + c10.equals(c10));
System.out.println("Should be false: " + c10.equals(c10Plus));
}
}
And this is my class file.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package a07;
/**
*
* #author Rian Ahmed (A00437022)
*/
public class Temperature {
// Instance Variables
public static final double DEG_C_PER_F = 9.0 / 5.0;
public static final double DEG_F_SHIFT = 32.0;
public double Degree;
public char Scale = 'C';
public static double FUZZ = 0.2;
// Constructors
public Temperature(double reqDegree, char reqScale) {
Degree = reqDegree;
if (reqScale == 'K') {
System.err.println("Illegal Scale: "+reqScale);
} else if (reqScale == 'k'){
Scale = 'K';
} else if (reqScale == 'c'){
Scale = 'C';
} else {
Scale = reqScale;
}
}
public Temperature(double reqDegree) {
Degree = reqDegree;
}
// Getters
public double getFahrenheit() {
if (Scale == 'C') {
return celsiusToFahrenheit(Degree);
} else {
return Degree;
}
}
public double getCelsius() {
if (Scale == 'F') {
return fahrenheitToCelsius(Degree);
} else {
return Degree;
}
}
// Setters
public static void setFuzz(double reqFuzz) {
if (reqFuzz >= 0) {
FUZZ = reqFuzz;
} else {
System.err.println("Illegal fuzz factor: "+reqFuzz);
}
}
public static double getFuzz () {
return FUZZ;
}
public static double celsiusToFahrenheit(double temp) {
return ((temp * DEG_C_PER_F) + DEG_F_SHIFT);
}
public static double fahrenheitToCelsius(double temp) {
return ((temp - DEG_F_SHIFT) / DEG_C_PER_F);
}
//toString
#Override
public String toString() {
return Degree + "°" + Scale;
}
}
what am i doing wrong here and how do i set the fuzz factor properly so the .equals() works properly?
also here is the guidelines that my professor provided:
Temperature (Advanced Objects and static Methods)
Synopsis
Create a class to hold a temperature value. Temperatures can be recorded in Celsius or Fahrenheit. The class provides three two constructors, two getters, a toString method, and an equality tester. It also provides static conversion functions and a static "fuzz" factor (to allow close temperatures to be judged equal) with its own getter and setter.
Hint: start by creating stubs for all the required methods and constructors. You can see the method calls in the testing program I provided. Don't start implementing methods until you can get the testing program to compile.
When you do start implementing methods, you should probably start with toString, then the constructors, and then the methods in the order they appear in the sample run.
Details
Your class allows a temperature to be recorded. The temperature is recorded either in Celsius or Fahrenheit -- for example, 10.0°C, 98.6°F -- but can be read back in either scale -- 50.0°F and 37.0°C for the temperatures just mentioned.
Note: the temperature is recorded in only one of the two scales. Do not have separate variables for the Celsius and Fahrenheit values.
Use a double value for the number of degrees, and a char value for the scale ('C' for Celsius or 'F' for Fahrenheit). The class has:
Two constructors: one that provides both the number of degrees and the scale; and one that provides just the number of degrees. (If not provided explicitly, use 'C' as the scale.)
Two static conversion methods: one to convert a number of degrees Fahrenheit to the corresponding number of degrees Celsius, and one to go the opposite way.
We've done these methods once or twice before. One multiplies the number of Celsius degrees by the number of Fahrenheit degrees per degree Celsius, then adds 32.0 (the Fahrenheit equivalent of zero degrees Celsius). The other requires a similar mathematical manipulation. It must first subtract 32.0 from the number of degrees Fahrenheit, then divide by the number of Fahrenheit degrees per degree Celsius.
Two getters: one gets the temperature in Fahrenheit, and the other gets it in Celsius. (If the temperature is already in the scale requested, you can just return the number of degrees. Otherwise, you must figure out the equivalent temperature in the other scale -- for which see the methods just above!)
A static "fuzz" factor, with its own getter and setter. Two temperature readings may be very close -- so close that we want to call them equal, even if they are a little bit off. For example, we might consider a body temperature of 98.62°F to be normal, even tho' it is not exactly 98.6°F. The client can set this factor to whatever non-negative value it wants. The factor is used by the equals method below. The default fuzz value is 0.2.
An equality testing method: which checks to see whether two temperatures are within the fuzz factor (see above) of each other in degrees Celsius.
Hint: Find the number of Celsius degrees for each temperature, and use Math.abs to find the absolute value of their difference. If it's less than (or equal to) the fuzz factor, then the temperatures should be considered equal.
Reminder: with this method, you ask one object whether it's equal to another object (in this case, both objects will be Temperatures).
Note for CS students -- this isn't actually the proper way to do an equals method! We will learn that in CSCI 1228. But do it this way for now.
For more information, see the chapter on Inheritance in the text.
A toString method: creates a String version of the temperature in the scale that it was recorded in. (For example, "10.0°C" or "98.6001°F".)
Note that there is no way to change the Temperature once it has been recorded. These objects are immutable -- can't be changed. They are like Strings that way.
More Details
If the client uses a small letter 'c' or 'f' for the scale, then we simply use the capital version of that letter. (Note: char variables don't have a toUpperCase method, so you have to check for and fix each of those separately.)
If the client tries to create a temperature with a scale that we don't recognize (like 'K' or 'M' or '*') we report the error to System.err and use the Celsius scale.
System.err is just like System.out, except it's supposed to be used for printing error messages instead of standard output. If you're using NetBeans, messages printed to System.err will appear in red letters and slightly out of order may appear relative to the standard output.
If the client tries to set the fuzz value to a negative number, then we report the error to System.err and leave the fuzz value unchanged.
The way to get a ° symbol in Java is to use the unicode character \u00b0. For example:
System.out.println("32.0\u00b0F")
will print
Write your own comparison function rather than overriding equals().
Something like: isEquals(float a,float b) { Math.abs(a - b) <= 10e-6 }

Implementing the Java comparable interface? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am not sure how to implement a comparable interface into my complex class. I have the following example code that I am using to try and get my head around it. I know it should be something like public double compareTo (Complex o) and something like that but I am not so sure on how to do it. Any suggestions on how i will implement it?:
import java.util.Scanner;
public class Complex implements Cloneable, Comparable {
private double real;
private double imag;
/*
* public Object clone() throws CloneNotSupportedException { Complex
* objClone = new Complex(); objClone.setReal(this.real);
* objClone.setImag(this.imag); return objClone; }
*/
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex(double real) {
this.real = real;
}
public Complex() {
}
public void setReal(double real) {
this.real = real;
}
public void setImag(double imag) {
this.imag = imag;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public void add(Complex num1, Complex num2) {
this.real = num1.real + num2.real;
this.imag = num1.imag + num2.imag;
}
public Complex subtract(Complex num) {
Complex a = this;
double real = a.real - num.real;
double imag = a.imag - num.imag;
return new Complex(real, imag);
}
public Complex multiply(Complex num) {
Complex a = this;
double real = a.real * num.real - a.imag * num.imag;
double imag = a.real * num.imag + a.imag * num.real;
return new Complex(real, imag);
}
public Complex divide(Complex c1, Complex c2) {
return new Complex((c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag),
(c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag));
}
public double absolute() {
return Math.sqrt(real * real + imag * imag);
}
public String toString() {
return this.real + " + " + this.imag + "i";
}
#Override
public Complex clone() throws CloneNotSupportedException {
super.clone();
return new Complex(real, imag);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the first set of complex numbers respectively: ");
double a = in.nextDouble();
double b = in.nextDouble();
Complex c1 = new Complex(a, b);
System.out.print("Enter the second set of complex numbers respectively: ");
double c = in.nextDouble();
double d = in.nextDouble();
Complex c2 = new Complex(c, d);
Complex result = new Complex(c, d);
result.add(c1, c2);
System.out.println("(" + a + " + " + b + "i) + (" + c + " + " + d + "i) = " + result.toString());
System.out.println("(" + a + " + " + b + "i) - (" + c + " + " + d + "i) = " + c1.subtract(c2));
System.out.println("(" + a + " + " + b + "i) * (" + c + " + " + d + "i) = " + c1.multiply(c2));
System.out.println("(" + a + " + " + b + "i) / (" + c + " + " + d + "i) = " + result.divide(c1, c2).toString());
System.out.println("|" + a + " + " + b + "i| = " + c1.absolute());
}
public double compareTo(Complex other) {
return this.getReal() - other.getReal();
}
}
First, the compareTo method of Comparator interface returns int, not double. Second, if you want to compare two double values in Comparator, you should never use a - b pattern. Instead, use predefined Double.compare method:
public int compareTo(Complex other) {
return Double.compare(this.getReal(), other.getReal());
}
This method carefully handles all the special values like -0.0 or NaN which are not very easy to handle manually. Note that similar methods exist for other types: Integer.compare, Long.compare and so on. It's preferred to use them.
Of course it should be noted that there's no natural order for complex numbers. Here you just compare the real parts, completely ignoring the imaginary parts.
From a mathematical standpoint, Complex numbers can't be ordered, and as such aren't a good fit for the the Comparable interface. To quote the wikipedia article:
Because complex numbers are naturally thought of as existing on a two-dimensional plane, there is no natural linear ordering on the set of complex numbers.
There is no linear ordering on the complex numbers that is compatible with addition and multiplication. Formally, we say that the complex numbers cannot have the structure of an ordered field. This is because any square in an ordered field is at least 0, but i2 = −1.
Having said that, there's nothing technically stopping you from implementing this interface. E.g., you can decide that you are sorting by the real part first and by the imaginary part second. Note that the contract of the compareTo method requires you to return an int, not a double. Also, you should define your class as extending Comparable<Complex> instead of a raw Comparable, so you don't have to mess around with casting and runtime type checking:
#Override
public int compareTo(Complex other) {
int realCompare = Double.compare(getReal(), other.getReal());
if (realCompare != 0) {
return realCompare;
}
return = Double.compare(getImag(), other.getImag());
}
EDIT:
The improvements in JDK 8's Comparator interface allow for a much more elegant implementation with the same behavior:
public int compareTo(Complex other) {
return Comparator.comparingDouble(Complex::getReal)
.thenComparingDouble(Complex::getImag)
.compare(this, other);
}
A few points worth noting.
As other answers have noted you generally should only implement Comparable if there's a natural ordering for instances of the class. As there's no natural ordering for complex numbers you likely shouldn't implement Comparable.
If you are going to provide a natural ordering then you should implement Comparable<Complex> to denote comparing to other instances of Complex (rather than comparing to other objects).
A better alternative to implementing Comparable is to provide one or more Comparator objects for your class that can be used to provide as many orderings as you want. For example:
public class Complex {
private double real;
private double imaginary;
public static final Comparator<Complex> COMPARE_BY_REAL =
Comparator.comparingDouble(Complex::getReal);
public static final Comparator<Complex> COMPARE_BY_IMAGINARY =
Comparator.comparingDouble(Complex::getImaginary);
public static final Comparator<Complex> COMPARE_BY_MODULUS =
Comparator.comparingDouble(Complex::getModulus);
private double getModulus() {
return Math.sqrt(real * real + imaginary * imaginary);
}
}
Then the user of the class can choose the ordering that makes sense to the use:
Optional<Complex> closestToOrigin = complexList.stream().min(Complex::COMPARE_BY_MODULUS);

Threeway Duel to the Death

Working on this project from my intro java class, heres the gist of what it needs to do --
In the land of Puzzlevania, Aaron, Bob, and Charlie had anargument over
which one of them was the greatest puzzler of all time. To endthe
argumentonce and for all, they agreed on a duel to the death. Aaronis a poor
shooter and only hits his target with a probability of 1/3. Bob isa bit better
and hits his target with a probability of 1/2. Charlie is an expertmarksman
and never misses. A hit means a kill and the person hit drops outof the duel.
To compensate for the inequities in their marksmanship skills, itis decided
that the contestants would fire in turns starting with Aaron,followed by Bob,
and then by Charlie. The cycle would repeat until there was oneman
standing. And that man would be remembered as the greatest puzzlerof all
time.
a. Write a function to simulate a single shot. It should usethe
following declaration:
voidshoot(bool& targetAlive, double accuracy, int&num_alive);
This would simulate someone shooting at targetAlive with thegiven
accuracy by generating a random number between 0 and 1. If therandom
number is less than accuracy, then the target is hit andtargetAlive should
be set to false. Appendix 4 illustrates how to generate randomnumbers.
For example, if Bob is shooting at Charlie, this could be invokedas:
shoot(charlieAlive,0.5, num_alive);
Here, charlieAlive is a Boolean variable that indicates if Charlieis alive. Test
your function using a driver program before moving on to stepb.
b. An obvious strategy is for each man to shoot at the most
accurate shooter still alive on the grounds that this shooter is the
deadliest and has the best chance of hitting back. Write a second
function named start Duel that uses the shoot function to simulate
an entire duel using this strategy. It should loop until only one
contestant is left, invoking the shoot function with the proper target
and probability of hitting the target according to who is shooting.
The function should return a variable that indicates who won the
duel.
c. In your main function, invoke the startDuel function 1,000 timesin
a loop, keeping track of how many times each contestant wins.
Output the probability that each contestant will win wheneveryone
uses the strategy of shooting at the most accurate shooter left
alive.
d. A counter intuitive strategy is for Aaron to intentionally misson his
first shot. Thereafter, everyone uses the strategy of shooting atthe
most accurate shooter left alive. This strategy means that Aaron is
guaranteed to live past the first round, since Bob and Charlie will
fire at each other. Modify the program to accommodate this new
strategy and output the probability of winning for each contestant.
So here is the code I'm working with... So far it goes through only once, but I'm not sure where I should put the loop? Also any other pointers in code would be much appreciated.
import java.util.Random;
public class Duelist
{
Random rnd = new Random();
static int aaron_wins,bob_wins,charlie_wins;
class Shooter
{
public static final int StartingHits = 1;
private String name;
private double accuracy;
private int hitsLeft = StartingHits;
public Shooter(String name, double accuracy)
{
this.name = name;
this.accuracy = accuracy;
}
public String getName() { return this.name; }
public double getAccuracy() { return this.accuracy; }
public boolean isAlive() { return this.hitsLeft > 0; }
public void takeHit() { this.hitsLeft--; }
public void shoot(Shooter target)
{
if (rnd.nextDouble() <= this.getAccuracy())
{
System.out.println(this.getName() + " hits " + target.getName());
target.takeHit();
if (!target.isAlive())
{
System.out.println(target.getName() + " dies.");
}
else
{
System.out.println(this.getName() + " misses " + target.getName());
}
}
}
}
private Shooter [] shooters;
public Duelist()
{
this.shooters = new Shooter []
{
new Shooter("Aaron", 0.33),
new Shooter("Bob", 0.5),
new Shooter("Charlie", 1)
};
}
public Shooter pickTarget(Shooter shooter) {
Shooter victim = null;
for(Shooter possibleVictim : this.shooters) {
if (!possibleVictim.isAlive()) { continue; }
if (shooter==possibleVictim) { continue; }
if (victim == null || possibleVictim.getAccuracy() > victim.getAccuracy()) {
victim = possibleVictim;
}
}
return victim;
}
public void fireAway() {
int currentShooter = 0;
int maxShooter = this.shooters.length;
while(true) {
Shooter shooter = this.shooters[currentShooter++];
if (shooter.isAlive()) {
Shooter victim = pickTarget(shooter);
if (victim!=null) {
shooter.shoot(victim);
} else {
System.out.println(shooter.getName() + " wins.");
if(shooter.getName().equals("Aaron"))
aaron_wins++;
else if(shooter.getName().equals("Bob"))
bob_wins++;
else if(shooter.getName().equals("Charlie"))
charlie_wins++;
break;
}
}
if (!(currentShooter<maxShooter)) { currentShooter=0; }
}
}
public static String beginDuel_alternative_strategy()
{
boolean aaronAlive = true;
boolean bobAlive = true;
boolean charlieAlive = true;
int num_alive = 3;
aaron_wins=bob_wins=charlie_wins=0;
String winner = "";
int round = 1;
do
{
if (aaronAlive)
{
if (round == 1)
{
if (charlieAlive)
shoot(charlieAlive, 1/3.0, num_alive);
else if (bobAlive)
shoot(bobAlive, 1/3.0, num_alive);
}
}
if (bobAlive)
{
if (charlieAlive)
shoot(charlieAlive, 0.5, num_alive);
else if (aaronAlive)
shoot(aaronAlive, 0.5, num_alive);
}
if(charlieAlive)
{
if (bobAlive)
shoot(bobAlive, 1.0, num_alive);
else if (aaronAlive)
shoot(aaronAlive, 1.0, num_alive);
}
round++;
num_alive--;
}while(num_alive > 1);
if (aaronAlive)
{
winner = "Aaron";
aaron_wins++;
}
else if(bobAlive)
{
winner = "Bob";
bob_wins++;
}
else
{
winner = "Charlie";
charlie_wins++;
}
return winner;
}
public static void shoot(boolean targetAlive, double accuracy, int number_alive)
{
Random rnd2 = new Random();
if (rnd2.nextDouble()< accuracy)
{
targetAlive = false;
number_alive--;
}
}
public static void main(String[] args)
{
Duelist duel = new Duelist();
duel.fireAway();
System.out.println("Using first strategy: \n");
System.out.println("Aaron won " + aaron_wins + " duels or " + aaron_wins * 100 + "%\n");
System.out.println("Bob has " + bob_wins + " duels or " + bob_wins * 100 + "%\n");
System.out.println("Charlie has " + charlie_wins + " duels or " + charlie_wins * 100 + "%\n");
System.out.println();
System.out.println("Using alternate strategy: \n");
System.out.println("Winner :" + beginDuel_alternative_strategy());
System.out.println();
System.out.println("Aaron has " + aaron_wins + " duels or " + aaron_wins * 100 + "%\n");
System.out.println("Bob won " + bob_wins + " duels or " + bob_wins * 100 + "%\n");
System.out.println("Charlie won " + charlie_wins + " duels or " + charlie_wins * 100 + "%\n");
}
}
The answer of your question is written in the requirements for your problem:
c. In your main function, invoke the startDuel function 1,000 timesin a loop, keeping track of how many times each contestant wins. Output the probability that each contestant will win when everyone uses the strategy of shooting at the most accurate shooter left alive.
// main() pseudocode:
Shooter[] shooters = new Shooter[3](); // or however java syntax is ...
// Set the strategy, name for each of the 3 shooters...
shooters[0].setName("..");
shooters[0].setStrategy(...);
// ...
// get some storage to count which player wins a round...
int[] winCounters = new int[3];
for( int i = 0; i < 1000; i++ )
{
int winner = startDuel(shooters); // returns index of winner...
winCounters[winner]++;
}
// ... output the statistics ....

call a method from another class

I'm in an intro programming class, in the lab that I'm currently working on we have to have two classes and pull the methods from one class, "Energy" and have them run in "Energy Driver."
I'm having trouble calling the methods (testOne, testTwo, testThree) over into "EnergyDriver"
public class EnergyDriver
{
public static void main(String [] args)
{
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + kineticE1);
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + kineticE2);
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + kineticE3);
}
}
public class Energy
{
public static void main(String [] args)
{
public double testOne;
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
}
public double testTwo;
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
}
public double testThree;
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
}
}
You must have only one main method in any one of class. To call a method from another class you can create an object of that class a call their respective method. Another way is by keeping the calling method to be static so you can access that method via Classname.Methodname.
public class EnergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + energy.testOne());
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + energy.testTwo());
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + energy.testThree());
}
}
class Energy
{
public double testOne()
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
public double testTwo()
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
return kineticE2;
}
public double testThree()
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
return kineticE3;
}
}
You can get the value of Kinetic Engergy 1,2,3 by using this code.
You can also use the below code which will use only one method to calculate different values by giving different arguments.
public class EngergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
double mass=25;
double velocity=70;
System.out.println(mass+ " kiolograms, "+velocity+"meters per second: Expected 61250," + " Actual " + energy.testOne(mass,velocity));
}
}
class Energy
{
public double testOne(double mass, double velocity)
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
}
Java programs have SINGLE point of entry and that is through the main method.
Therefore in a single project only one class should have the main method and when compiler will look for that when you run it.
Remember that static methods cannot access non static methods hence main is static therefore it can not access testone two nor three UNLESS you create and object of that type. Meaning in the main method you can have Energy e = new Energy() then access those methods that were not declared with keyword static like e.testone() .
However take note that non static methods can access static methods through Classname.Method name because keyword static entails that only a single copy of that method/variable exists therefore we do not need an object to access it since only one copy exists.
I recommend watching the Java videos from Lynda.com or reading the books Java Head First and Java How To Program (Deitel,Deitel) to give you a boost on your Java knowledge they come with alot of exercises to enhance your knowledge.
Also there are plenty of other questions like this on SO search for them

Cannot understand enums in java

I was looking at an example code provided in my book
enum Coin
{
PENNY(1),
NICKEL(5),
DIME(10),
QUARTER(25);
private final int denomValue;
Coin(int denomValue)
{
this.denomValue = denomValue;
}
int denomValue()
{
return denomValue;
}
int toDenomination(int numPennies)
{
return numPennies / denomValue;
}
}
public class Coins
{
public static void main(String[] args)
{
if (args.length == 1)
{
int numPennies = Integer.parseInt(args[0]);
System.out.println(numPennies + " pennies is equivalent to:");
int numQuarters = Coin.QUARTER.toDenomination(numPennies);
System.out.println(numQuarters + " " + Coin.QUARTER.toString() +
(numQuarters != 1 ? "s," : ","));
numPennies -= numQuarters * Coin.QUARTER.denomValue();
int numDimes = Coin.DIME.toDenomination(numPennies);
System.out.println(numDimes + " " + Coin.DIME.toString() +
(numDimes != 1 ? "s, " : ","));
numPennies -= numDimes * Coin.DIME.denomValue();
int numNickels = Coin.NICKEL.toDenomination(numPennies);
System.out.println(numNickels + " " + Coin.NICKEL.toString() +
(numNickels != 1 ? "s, " : ", and"));
numPennies -= numNickels*Coin.NICKEL.denomValue();
System.out.println(numPennies + " " + Coin.PENNY.toString() +
(numPennies != 1 ? "s" : ""));
}
System.out.println();
System.out.println("Denomination values:");
for (int i = 0; i < Coin.values().length; i++)
System.out.println(Coin.values()[i].denomValue());
}
}
If enum is like a class, is it possible to have the same name for a method and field inside a class, as it has been done here with denomValue?
Why is it calling int numQuarters = Coin.QUARTER.toDenomination(numPennies); in this manner? Is toDenomination() static by default?
In the above case, what is the value of denomValue field? The output for this program hints that it should be equal to QUARTER. But how does that work? Is Coin.QUARTER equivalent to creating a coin object and passing QUARTER as it's constructor argument?
Each of PENNY, NICKEL are instances of Coin class and are static, so they can be accessed as Coin.PENNY.
So when you do :
Coin.QUARTER.toDenomination(numPennies)
you are accessing the QUARTER instance of coin class and calling its toDenomination() method which is an instance method being called on QUARTER instance.
When you do:
PENNY(1) //this actually calls the constructor with one integer argument of Coin class
To check that PENNY is instance of Coin class:
System.out.println(Coin.PENNY.getClass()); //Will show you Coin
Enums are special classes as:
They are constant classes.
The enum values can only be accessed statically.
Hence why Enums have a private constructor.
Once you have gotten the value, the declared methods and attributes can be accessed like an ordinary class.
the values of denomValue depends on the Enum value declared in Coin enum. For example: PENNY enum denomValue is 1 and will always be 1.

Categories

Resources