How do this subclass interact with the main class - java

I'm stuck on a mock exam question. I created a class called Power which allowed a number to be raised to any power.
The third part of the question asks me to create another class BoundedPower which would extend Power. I was given the MAX-X variable (x cannot exceed this value) and told that the BoundedPower class must: behave like the Power class, use a constructor and use thepowN method.
My code is below, i am not sure what to do to make the BoundedPower class work.
public class Power {
private double x = 0;
Power(double x) {
this.x = x;
}
public double getX() {
return x;
}
public double powN(int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
public static void main(String[] args) {
Power p = new Power(5.0);
double d = p.powN(3);
System.out.println(d);
}
}
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
// invariant: x <= MAX_X
Power x;
BoundedPower(double x) {
super(x);
// this.x=x; x is private in Power class
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * getX();
}
return result;
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}

There is no need for that instance Power variable x in your class. Any BoundedPower instance IS a Power instance, and as such, to reference a method from Power, do super.blah(), so for x.getX(), do super.getX()
Also, in your comments, you said this.x=x fails because its private. When you do the super call, it calls the constructor of the superclass (Power), which sets x there, so there is no need for this.x=x

public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
BoundedPower(double x) {
super(x);
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
return super.powN(n);
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
You don't have to copy your computation formular to the subclass (just call super.powN(..)). You also don't need another instance of Power within BoundedPower.

This is probably what they had in mind:
public class Power {
public double powN(double x, int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
}
public class BoundedPower extends Power {
private final double maxX;
public BoundedPower(double maxX) {
this.maxX = maxX;
}
public double powN(double x, int n) {
if (x > maxX) {
throw new IllegalArgumentException("x value [" + x + "] " +
"greater than expected max [" + maxX + "]");
}
return super.powN(x, n);
}
}

I would do it in a different way. From what you're saying the BoundedPower class makes sense only for a bounded x (up to MAX_X).
Consequently, I would not allow the creation of an object with an x greater than MAX_X (i.e. a BoundedPower object cannot exist for unbounded x's)
So the implementation would be exactly as the the Power implementation excepting the way you build BoundedPower instances : you first check whether it makes sense to build it
public class BoundedPower extends Power {
private static final double MAX_X = 1000000; //makes no sense to be public
public static BoundedPower newBoundedPower(int n)
throws IllegalNumberException{
if(x > MAX_X) throw new IllegalNumberException();
return new BoundedPower(x);
}
private BoundedPower(double x) {
super(x);
}
}

Related

Create a Single Random Value to Share Across Classes Java

Final(?) edit:
Leonardo Pina's solution looks like what I needed. Thank you all for your input! My code is now:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And the implementation in the other class:
public class Damage {
Roll r;
Damage(Roll r) {
this.r = r;
}
public int damageOut() {
int a = r.getR(); //roll value
return a * 2; //test math on r
}
}
Edit:
Thank you for the responses. However, it seems my use of this method was not clear. Apologies! This is what I need:
Call Roll class, get e.g. "12"
OtherClass1 receives "12" from Roll via getter
OtherClass2 also receives "12" from Roll via getter
Call Roll class again, get a new random number, e.g. "48"
OtherClass1 receives "48" from Roll via getter
OtherClass2 also receives "48" from Roll via getter
Using the solutions provided, Roll creates a single random number and never creates a new one again. I need Roll to create random numbers on demand, and then share that random number with other classes. I do not want it to only generate one number and then stop. I hope this makes sense. Thank you for the responses so far!
I have searched for and read the other threads of a similar topic (including this one, which is how I tried to solve my problem), but the methods I have tried have failed. I need to create a single random value and then use that same value across multiple classes.
My random class:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And a class where I call for the static value from the random class:
public class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
When I call the getter from OtherClass, the value is different than the getter from Roll. I would expect them to be the same value.
I call the values for testing like so:
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
Any guidance would be greatly appreciated. Have a good day.
When you create a new instance of OtherClass you also create a new instance of Roll, therefore, the rolls are different.
You need to make sure you are getting the value R from the same object Roll.
This could be achieved by using a singleton pattern for the Roll class, or you could specify the Roll object you want to use to get values, this way you could have several rolls for different purposes. i.e.
Edit:
Answering your edit: to get a new number, you should update the value of r in the Roll class whenever you generate a new value, for example, instead of returning a value, the level() method could update the r variable:
public final class Roll {
private static final Random r1 = new Random();
// We now attribute a value to r uppon construction
private final int r;
public Roll() {
level();
}
// Whenever level() is called the value of r is updated
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
this.r = r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class Game {
public static void main(String[] args) {
// Create the Roll obj
Roll myRoll = new Roll();
// Initialize the other objs with myRoll
Board board = new Board(myRoll);
Player player = new Player(myRoll);
// Do your comparison
int b = board.getRoll();
int p = player.getRoll();
// EDIT: get a new value
myRoll.level();
// Do your comparison once more
b = board.getRoll();
p = player.getRoll();
}
class Board {
Roll r;
Board(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
class Player {
Roll r;
Player(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
}
Probably the simplest way to make it work would be to field r in class Roll as static, so that the Roll class looks like this:
ublic final class Roll {
private static final Random r1 = new Random();
private static final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
Or second approach would be to make Roll class a singleton.
Edit:
Since you have changed the intent of the question, and from what I understand you should look into Observer design pattern. It may be helpful for your case.
As someone said in the comments, you should follow the singleton design pattern, meaning that your variable r should be unique across all Roll class instances. To do this, your code will have to look something like this:
public class RandomTest {
public static void main(String[] args) {
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
}
}
class Roll {
private static Random r1 = new Random();
private static int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
How about sharing the Roll instance?
Roll roll = new Roll();
// roll.roll(); // Unclear how you "refresh" the data
int r = roll.getR();
OtherClass other = new OtherClass(roll);
int o = other.getR();
assert(o == r);
class OtherClass {
private final Roll roll;
public OtherClass(Roll roll) {
this.roll = roll;
}
public int getR() {
return roll.getR();
}
}
Tip: I think a Dice class with a roll() method makes more sense.

Different variable output from same method JAVA genetic algorithm

So i am trying to build a genetic algorithm on java i stuck on getting
fitness of my population here 3 classes from my project:
Class Individu
public class Individu {
int Popsize=4;
int Health[]= new int[Popsize];
int Attack[]= new int[Popsize];
int Atspeed[]= new int[Popsize];
int Move[]= new int[Popsize];
int health,attack,lifetime,dmgdone,attspeed,range,move;
double fitness;
double Pitness[]= new double[20];
Random random = new Random();
public int setHealth(){
health = random.nextInt(150 - 75) + 75;
return health;
}
public int setAttack(){
attack = random.nextInt(10 - 5) + 10;
return attack;
}
public int setAttspeed(){
attspeed = random.nextInt(3 - 1) + 3;
return attspeed;
}
public int setMoveSpeed(){
move = random.nextInt(8 - 4) + 1;
return move;
}
public int getGeneHealth(int index) {
return Health[index];
}
public int getGeneAttack(int index) {
return Attack[index];
}
public int getGeneAtspedd(int index) {
return Atspeed[index];
}
public int getGeneMove(int index) {
return Move[index];
}
public void setGene(int index, int value) {
Health[index]=value;
Attack[index]=value;
Atspeed[index]=value;
Move[index]=value;
fitness = 0;
}
public int size() {
return Popsize;
}
public double[] GenerateIndividual(){
for (int i = 0; i <Popsize; i++) {
Health[i]=setHealth();
Attack[i]=setAttack();
Atspeed[i]=setAttspeed();
Move[i]=setMoveSpeed();
}
return Pitness;
}
Class Fitness
public class Fitness {
Individu individu= new Individu();
double fitness;
double Pitness[]= new double[20];
public double getFitness(){
individu.GenerateIndividual();
for (int i = 0; i <=3; i++) {
fitness=
individu.getGeneHealth(i)+individu.getGeneAtspedd(i)+
individu.getGeneAttack(i)+
individu.getGeneMove(i));
fitness=fitness/171;
Pitness[i]=fitness;
System.out.println("Health from class
fitness"+individu.Health[i]);
}
return fitness;
}
}
Main Class
public class main {
public static void main(String[] args) {
Individu aaa=new Individu();
Fitness bbb= new Fitness();
bbb.getFitness();
aaa.GenerateIndividual();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
for (int i=0; i<=3; i++){
//System.out.println("Fitness ");
System.out.println("Generasi ke :"+i+1);
System.out.println("Health "+aaa.getGeneHealth(i));
System.out.println("Attackspeed "+aaa.getGeneAtspedd(i));
System.out.println("Attack "+aaa.getGeneAttack(i));
System.out.println("movementSpeed "+aaa.getGeneMove(i));
}
}
}
What i struggle is when i run this script i got 2 double value from 1 variable first value is from Fitness class as i printed here
System.out.println("Health from class fitness"+individu.Health[i]);
and second variable i printed here from Main Class
System.out.println("Health "+aaa.getGeneHealth(i));
that 2 variable is always have different value causing my fitness and my generation is not correlated each other.
My question is how to make this 2 variable print same value?
Well, aside from the many problems I can detect about the essentials of Genetic Algorithms, I see 'individu' and 'aaa' are two different Java objects.
Individu aaa=new Individu();
aaa.GenerateIndividual();
and
Individu individu= new Individu();
individu.GenerateIndividual();
Since your Health and Fitness are randomly generated on GenerateIndividual(), both 'aaa' and 'individu' will get different Health values.
I strongly recommend you to review GA essentials, since I can see many conception errors in your system.

Why won't my method print out?

I've made a main method in one class and a lot of other small methods in another class. When I call on them in my main method using their location and making sure that they would outprint if I called on them, they still don't outprint. Only the print two methods show any output. I'm not sure how to go about fixing it so I haven't tried many things yet. Could you look at my code and check why they aren't working?
Update: I've managed to get all the line in the main method except for 28 working with the help I received. Now all that's left is that one output. I've changed the code so it works a bit better and will shut down if it doesn't output, but the output is still missing.package rational;
My Main Method
package rational;
/**
*
* #author Dominique
*/
public class Rational {
public static String number() {
rational1 number= new rational1(27, 3);
String r3= number.printRational(number);
return r3;
}
public static void main(String[] args) {
rational1 number= new rational1(27,3);
System.out.println(number());
String r3=number();
System.out.println(rational1.toDouble(27,3 ));
rational1.add(number);
rational1.invert(r3, number);
rational1.negate(r3, number);
rational1.toDouble(27, 3);
}
}
My Other Method Class
package rational;
/**
*
* #author Dominique
*/
public class rational1 {
public int top;
public int bottom;
public rational1 () {
this.top = 0;
this.bottom = 0;
}
public rational1(int top, int bottom){
this.top=top;
this.bottom=bottom;
}
public String printRational(rational1 r1){
String r3=("Your fraction is "+String.format(r1.top+" / "+r1.bottom));
return r3;
}
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('s');
if (index != -1) {
System.out.print(r2.substring(0, index+1));//works
System.out.println(" "+r1.bottom + "/" + r1.top);
index++;
}
else {
System.exit(0);
}
}
public static void negate(String r2, rational1 r1){
int index = r2.indexOf('-');
if (index != -1) {
String stringValueOf = String.valueOf(r1.top);
System.out.println(r2.substring(0, 17));//works
System.out.println(r1.bottom+"/"+stringValueOf.substring(1));
index++;
}
}
public static double toDouble(int one, int two){
int three= one/two;
return three;
}
public static double gcd( double a, double b)
{
double r = a % b;
if (r != 0)
{
return gcd(b, r );
}
else
{
return b;
}
}
public static double reduce(double t, double b){
double numberone=gcd(t, b);
double pick=numberone*(b/t);
return pick;
}
public static double add(rational1 r1){
double pickone=(r1.top);
double choice= pickone+pickone;
double choice2=reduce(choice, r1.bottom);
return choice2;
}
}
So the problem is in invert method:
public static void invert(String r2, rational1 r1){
int index = 0;
while (index < 1) {
if (r2.charAt(index) == '/') {
System.out.print(r2.substring(0, 17));
System.out.print(r1.bottom+"/"+r1.top);
index++;
}else{
System.exit(0);
}
`}
}
This method immediate checks the character at r2.charAt(index) == '/'), but this is never the case. Because the character at index = 0 is 'Y' from the printRational method. Because that's not the case then System.exit(0) gets called which immediately ends the program without running the rest of the program.
I believe that this code will work.
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('/');
if (index != -1) {
index++;
}
else {
System.out.print(r2.substring(0, index));//works
System.out.print(r1.bottom + "/" + r1.top);
}
}
The print method does not necessarily flush the buffer to the screen. Try replacing the print method with the println method.
Once this is in rational package., try to change the system.out.print to system.out.println .Basically all your codes are okay. Try look at this link.
Click [here] (http://introcs.cs.princeton.edu/java/92symbolic/Rational.java.html)!

Java Interfaces/Callbacks for Using 1 of 2 Possible Methods

I have read up on Java Interfaces (callbacks) because I was told by a professor I should use callbacks in one of my programs. In my code, there are two Mathematical functions I can 'pick' from. Instead of making a method activate() and changing the code inside (from one function to the other) when I want to change functions, he said I should use callbacks. However, from what I've read about callbacks, I'm not sure how this would be useful.
EDIT: added my code
public interface
//the Interface
Activation {
double activate(Object anObject);
}
//one of the methods
public void sigmoid(double x)
{
1 / (1 + Math.exp(-x));
}
//other method
public void htan(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = Math.tanh(x[i]);
}
}
public double derivativeFunction(final double x) {
return (1.0 - x * x);
}
}
If you want to use interfaces something like this would work.
I have a MathFunc interface that has a calc method.
In the program I have a MathFunc for mutliplication and one for addition.
With the method chooseFunc you can choose one of both and with doCalc the current chosen MathFunc will do the calculation.
public interface MathFunc {
int calc(int a, int b);
}
and you can use it like that:
public class Program {
private MathFunc mult = new MathFunc() {
public int calc(int a, int b) {
return a*b;
}
};
private MathFunc add = new MathFunc() {
public int calc(int a, int b) {
return a+b;
}
};
private MathFunc current = null;
// Here you choose the function
// It doesnt matter in which way you choose the function.
public void chooseFunc(String func) {
if ("mult".equals(func))
current = mult;
if ("add".equals(func))
current = add;
}
// here you calculate with the chosen function
public int doCalc(int a, int b) {
if (current != null)
return current.calc(a, b);
return 0;
}
public static void main(String[] args) {
Program program = new Program();
program.chooseFunc("mult");
System.out.println(program.doCalc(3, 3)); // prints 9
program.chooseFunc("add");
System.out.println(program.doCalc(3, 3)); // prints 6
}
}

Java- Involving objects and multiple classes

My problem is that for the getTime(); command, you need all of the speed, handling, xcord, ycord, and the terrainDifficultry variables to have an answer, yet I can only call getTime(); from the mb1 class. Basically, I keep getting 0.0 when i get to System.out getTime() and I don't know how to fix it.
import java.util.Scanner;
public class Main_MoonRace {
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter the speed of the moonbuggy as an integer.");
int s = keyboard.nextInt();
System.out.println("Enter the handling of the moonbuggy (between 0-0.9)");
double h = keyboard.nextDouble();
moonbuggy mb1 = new moonbuggy(s,h);
System.out.println("Enter the x-coordinate of where the moonbuggy will be headed to as an integer.");
int xcord = keyboard.nextInt();
System.out.println("Enter the y-coordinate of where the moonbuggy will be headed to as an integer.");
int ycord = keyboard.nextInt();
System.out.println("Enter the difficulty of the terrain that the moonbuggy will be experiencing (integer from 1-10).");
int terrainDifficulty = keyboard.nextInt();
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
System.out.println(mb1.getTime());
}
}
moonbuggy.java
public class moonbuggy {
private int speed = 1;
private double handling = 0;
moonbuggy(){
return;
}
moonbuggy(int s, double h){
speed = s;
handling = h;
return;
}
public void setSpeed (int s){
speed = s;
}
public void setHandling (double h){
handling = h;
}
public int getSpeed(){
return speed;
}
public double getHandling(){
return handling;
}
MoonLocation obj1 = new MoonLocation();
public double getTime(){
double time = (((obj1.getdistance())/(getSpeed()))*(obj1.getTerrain())*(1-(getHandling())));
return time;
}
}
MoonLocation.java
public class MoonLocation {
private int x = 0;
private int y = 0;
private int terrain = 1;
MoonLocation(){
return;
}
MoonLocation(int xcord, int ycord, int terrainDifficulty){
x= xcord;
y = ycord;
terrain = terrainDifficulty;
return;
}
public void setX (int xcord){
x = xcord;
}
public void setY (int ycord){
y = ycord;
}
public void setTerrain (int terrainDifficulty){
terrain = terrainDifficulty;
}
public int getX () {
return x;
}
public int getY () {
return y;
}
public int getTerrain () {
return terrain;
}
public double getdistance () {
double distance = Math.sqrt((Math.pow(x,2))+(Math.pow(y,2)));
return distance;
}
}
Have a look at this part of code in your moonbuggy class (note that by convention a class should always start with uppercase in java).
MoonLocation obj1 = new MoonLocation();
public double getTime(){
double time = (((obj1.getdistance())/(getSpeed()))*(obj1.getTerrain())*(1-(getHandling())));
return time;
}
You instanciate a MoonLocation without any parameters, then you access it in your getTime method. This explain why you always get 0.0 as result when calling getTime.
Now modify your getTime method to
public double getTime(MoonLocation location){
return (((location.getdistance())/(getSpeed()))*(location.getTerrain())*(1-(getHandling())));
}
Notice that I removed the time variable as it is completly useless there.
And change in your main
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
System.out.println(mb1.getTime());
To
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
System.out.println(mb1.getTime(mL1));
Also, please remove the unused MoonLocation obj1 = new MoonLocation() in your moonbuggy class.
The Problem lies with your code. In the first place, you are creating an object of MoonLocation in Main_MoonRace class under main() method as :
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
Here, an object of MoonLocation is created and initialized with xcord, ycord, and terrainDifficulty values.
Now, in your MoonBuggy class, again you are creating an object of MoonLocation as :
MoonLocation obj1 = new MoonLocation();
Here, only an empty object of MoonLocation class is created.
Now, when you call :
obj1.getDistance(); It will return 0 only.
Below is the corrected code for MoonBuggy class.
public class Moonbuggy {
private int speed = 1;
private double handling = 0;
Moonbuggy(){}
Moonbuggy(int s, double h){
speed = s;
handling = h;
}
public void setSpeed (int s){
speed = s;
}
public void setHandling (double h){
handling = h;
}
public int getSpeed(){
return speed;
}
public double getHandling(){
return handling;
}
private MoonLocation obj1;
public MoonLocation getObj1() {
return obj1;
}
public void setObj1(MoonLocation obj1) {
this.obj1 = obj1;
}
public double getTime(){
double time = (((obj1.getdistance())/(getSpeed()))*(obj1.getTerrain())*(1-(getHandling())));
return time;
}
}
and an addtion in the main() method :
MoonLocation mL1 = new MoonLocation(xcord,ycord,terrainDifficulty);
mb1.setObj1(mL1); // set the MoonLocation object
System.out.println(mb1.getTime());
Now , you will get the proper output

Categories