Update constructor using method - java

I have a game app and I want it to update the constructor strength value when I call the levelUp() method.
public Hero(String heroname, double strength, double strength_gain){
this.heroname = heroname;
this.hp = (int) (200+20*strength);
this.strength_gain = strength_gain;
}
public void levelUp(){
this.strength = strength + strength_gain;
}
But when i do System.out.println(hero.hp); after calling levelUp() it returns the first value.

One way to always get an up-to-date value for a calculation that depends on other variables/inputs is to calculate it on demand (useful for simple calculations, such as the one you have).
EDIT: I realized that you might want to have an hp and a maxHp if your hero can actually lose/gain hp so I edited the example to take that into account.
public class Hero {
// ...
public int hp;
public Hero(String heroname, double strength, double strength_gain){
this.heroname = heroname;
this.strength = strength; // <-- don't forget to save the initial strength as well
this.strength_gain = strength_gain;
this.hp = getMaxHp();
}
public int getMaxHp() {
return (int) (200 + 20 * strength);
}
public void levelUp(){
strength = strength + strength_gain;
// decide if leveling up also heals your hero?
hp = getMaxHp();
}
// ...
}
Elsewhere in code you can access both the .hp and the .getMaxHp().
System.out.println(hero.hp);
System.out.println(hero.getMaxHp());
If the calculations would be heavy, then using a boolean as a change flag and lazily recalculating only once per change and only when required would make more sense.

Related

Creating a Vehicle Program

Right now I'm doing some tasks from a java e-book that I've acquired, and unfortunately, I'm stuck. The main thought of this program is to create a Vehicle class, which along with a test program can increase, decrease and break the current speed.
The starting speed should be 0. I want the user to specify what speed the car should drive to (for an example 90 km/h). After hitting the speed(90 in this case) I want the program to ask the user if he wants to decrease the speed to a given value, stay at the same speed, or break to 0. Should all of this be done in the testprogram, or should it be implemented into the Vehicle class?
I'm supposed to create a program from the following UML: https://i.stack.imgur.com/01fgM.png
This is my code so far:
public class Vehicle {
int speed;
//Constructor
public Vehicle () {
this.speed = 0;
}
public void increaseSpeed (int differenceInc) {
this.speed += differenceInc;
}
public void decreaseSpeed (int differenceDec) {
this.speed -= differenceDec;
}
public void brake() {
}
public int getSpeed () {
return this.speed;
}
}
And this is my empty test class.
public class VehicleTest {
public static void main(String[] args) {
Vehicle golf = new Vehicle();
//Speed which should be accelerated to:
Vehicle myHybrid = new Vehicle();
System.out.println("You've hit the given speed. Do you want to stay at this speed, break, or decrease to another given speed?");
}
}
Well , first of all, welcome to Stack Overflow.
If you want a method to accept arguments (parameters) then you must declare said arguments and the arguments' types in the mehtod declaration:
public void increaseSpeed (int augmentValue) {
this.speed += augmentValue;
}
You're also asking about software design: "should the component (Vehicle) user or client be able to set the augment value of the increaseSpeed mehtod?" . The answer relies on the design of said component. If your method will accept an argument then perhaps the method should also validate the input value and establish pre and post conditions.
Hope this helps.
Probably the idea is to take an int for increaseSpeed(), so that you can increase the speed by that given integer. Also add the logic for hitting the speed limit in your increaseSpeed method.
So...
public void increaseSpeed (int amount) {
if (speed + amount < MAX_SPEED) { // Where MAX_SPEED is a static final int of value 90
this.speed += amount;
} else {
System.out.println("Max speed reached. Want to exceed (y/n)?");
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0);
if (c == 'y') {
this.speed += amount;
}
}
}
You can do the same for decreaseSpeed(), of course. Don't forget to check if decreasing the speed doesn't result in a negative speed (unless, you consider a negative value of speed to be driving in reverse.
By the way, here I have hard-coded MAX_SPEED for simplicity. This is, of course, dependent on the road you are driving, so it is probably better to do this differently (e.g., a Road class that includes the particular attributes of a given road, or by passing both an integer for the amount you want to speedup with and an integer for the maximum speed).

How to make calculation inside class field in Java?

So I created Saving class, created also setters and getters. Now I need u method, which will calculate the total amount of deposits.
public class Saving {
private double deposits;
private double totalAmountOfDeposits;
public double getDeposits()
{
return deposits;
}
public void setDeposits(double deposits)
{
this.deposits = deposits + deposits;
}
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
}
When I use this class in the program I got a wrong calculation. The program just add first value of deposit to the first value.
import java.util.Scanner;
public class SavingDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Saving save = new Saving();
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
}
}
And here is the output:
Deposit amount
12
Deposit amount
34
Deposit amount
56
The total amount has been deposited is 24.0
As you can see its just added 12 to 12. Just want to mention that I'm totally new in programming. Les than a month.
I see two problems in your code. Take a look at the commented line. The reason you are seeing 12 + 12 is because that is exactly what you are instructing the JVM to do.
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
Secondly, it looks like you may have a design flaw in your implementation of the Saving class.
You'll want to brush up on variable scope
If you take a look at your implementation on your total:
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
You have the total starting at 0 every time this method getTotalAmountOfDeposits() is called. the total variable in this method is local to it's method. So what you currently have is a method variable
You'll want to do some research into class variable. This will maintain that the instance of the object will have this variable assigned through the life cycle of the instantiated object.
When you have variables of the same name, you can get the instance variable with this keyword.
So when dealing with your setter
public void setSomething(double something) {
this.something // class variable
something // method variable
}
If you want your object to maintain state, you can set it on your object itself, and have your set deposit modify that state. Some pseudo code to get you moving forward.
public class Saving {
private double totalAmountOfDeposits; // you can modify this value with public methods
public void setDeposit(_) {
// Setter implementation
// increment totalAmountOfDeposits;
public double getTotalAmountOfDeposits(_)
// return totalAmountOfDeposits;
}
You should write a method
public void addDeposits(double deposits)
{
this.deposits = this.deposits + deposits;
}
and change setDeposits to
public void setDeposits(double deposits)
{
this.deposits = deposits;
}
after this call addDeposits to add deposits
To eliminate confusion within the Saving Class change the argument name for the setDeposits() method to double newDeposit instead of double deposits which is also a class field name. Although the construct is legal it does make it a wee bit confusing. Inside the setDeposits() method use:
this.deposit+= newDeposit;
As a matter of fact, you can get rid of the deposits field altogether since you also have the field named totalAmountOfDeposits. Use that instead:
this.totalAmountOfDeposits+= newDeposit;
You might also want a clearDeposits() method in your Saving Class:
public void clearDeposits() {
this.totalAmountOfDeposits = 0.0;
}
Your getTotalAmountOfDeposits() method within the Saving Class doesn't really make any sense either. Since you are always summing deposits anyways you can just return what is held within the totalAmountOfDeposits field:
public double getTotalAmountOfDeposits() {
return totalAmountOfDeposits;
}
The above method is would now of course be very mush the same as the getDeposits() method which could be changed to getTotalDeposits(). You can then change the getTotalAmountOfDeposits() method name to getTotalNumberOfDeposits() and add a additional class field named numberOfDeposits:
private double totalAmountOfDeposits;
private int numberOfDeposits = 0;
public double getTotalDeposits() {
return totalAmountOfDeposits;
}
public int getTotalNumberOfDeposits() {
return numberOfDeposits;
}
and in your setDeposits() method add the code line:
numberOfDeposits++;
So that it would look something like:
public void setDeposits(double newDeposit) {
totalAmountOfDeposits+= newDeposit;
numberOfDeposits++;
}
If you do add a clearDeposits() method to your Saving Class then don't forget to add the code line: numberOfDeposits = 0; into that method as well. It might now look something like:
public void clearDeposits() {
totalAmountOfDeposits = 0.0;
numberOfDeposits = 0;
}
You also have some issues within your main() method of your SavingDemo Class. Take a real close look at each call you make to the setDeposits() method for each value the User supplies. Each User supplied value goes into a specific double type variable name. Is that what you are passing to the setDeposits() method? ;)
Once you've got all that taken care of you can display to console:
System.out.println("The total amount has been deposited is " +
save.getTotalDeposits() + " by making " +
save.getTotalNumberOfDeposits() + " deposits.");

Methods not working with tester in java

I'm a newbie coder here currently taking a computer science class based on java. I'm having issues with a program I'm supposed to be writing and I can't seem to figure it out regardless of what I look up, so I'm asking on here.
The instructions say: Create a class. Create a method within the class called printDimensions() that displays the dimensions of a letter-size(8.5x11 inches) sheet of paper in millimeters. There are 25.4 millimeters per inch (constant value). Use constants and comments in the method. It also says (make use of printf to limit the number of decimal places in your method.
As of right now I am stuck in the middle of using the print statement and the return value for the method. I also have a tester that I am using to test the code, but I'm getting BOTH the print statement AND the return value, which I don't believe is correct.
public class Task01
{
// final dimensions of the paper
private double dimensions;
// width of the paper which is 8.5
private double paperWidth;
// length of the paper which is 11
private double paperLength;
public Task01(){
dimensions = 0;
paperLength = 0;
paperWidth = 0;
}
public double printDimensions()
{
final double LENGTH = 11; // inches
final double WIDTH = 8.5; // inches
final double MM_PER_INCH = 25.4; // millimeters per inch
paperLength = LENGTH * MM_PER_INCH;
paperWidth = WIDTH * MM_PER_INCH;
System.out.printf("The dimension are: " + paperLength + " x " + paperWidth);
return dimensions;
}
}
For the tester, I have a seperate class that I use to call the methods I create by creating a new object for that task.
public class Tester
{
public static void main(String[] arg)
{
System.out.println("The task begins now: ");
// creating a new object for the task
Task01 task01 = new Task01();
System.out.println(task01.printDimensions());
}
}
Change this line:
public double printDimensions()
To this
public void printDimensions()
then remove the return statement at the end of that method
You have two options. You can remove the line System.out.printf("The dimension are: " + paperLength + " x " + paperWidth); from the printDimensions methods. Then your tester class just create an instance of Task01 and call the method in a print statement which would look something like this:
public static void main(String[] args) {
Task01 t = new Task01();
System.out.println(t.printDimensions);
}
The other option as already stated is to change the method type to void rather than double and remove the return statement. Then call it like this:
public static void main(String[] args) {
Task01 t = new Task01();
t.printDimensions();
}

Abstract Concept Assignment [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So my questions are geared directly to my homework. Before you ask, yes I've looked at other questions and I have looked at the java docs to try and help me but I only understand so much..
You have become a restaurant mogul. You own several fast food chains. However, you now need to set a standard that all of your fast food chain must follow in order to have your software be uniform across the board. There will be some rules that will be the same for all restaurants.
Create an Abstract Class named Restaurant
Create a function/method that will print the name of the restaurant when called.
Create an abstract function/method named total price
Create an abstract function/method named menu items
Create an abstract function/method name location
Create a Class called McDonalds that extends Restaurant
Implement all abstract methods
Add logic so that the total price method/function will give the total price of the meal including a 6% tax
Add a method that returns a Boolean named hasPlayPlace. Which returns true when this location has a playplace
Create a Constructor that will set the name of the Mcdonalds, location, and hasPlayPlace
public class McDonalds extends Restaurant {
private String name;
private String location;
private boolean hasPlayPlace;
Scanner input = new Scanner(System.in);
public McDonalds (String name, String location, boolean hasPlayPlace) {
setName(name);
setLocation(location);
setHasPlayPlace(hasPlayPlace);
}
McDonalds location1 = new McDonalds("McDonalds", "Kirkman", false);
McDonalds location2 = new McDonalds("McDonalds 2", "International Dr.", true);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location){
this.location = location;
}
public boolean isHasPlayPlace() {
return hasPlayPlace;
}
public void setHasPlayPlace(boolean hasPlayPlace) {
this.hasPlayPlace = hasPlayPlace;
}
public void totalPrice() {
double totalPrice = 0;
double tax = 0.06;
totalPrice += (totalPrice * tax);
}
public void menuItems() {
//some syntax is wrong in this method
double mcChicken = 1;
double fries = 1.25;
System.out.println("1. Mc Chicken $1");
System.out.println("2. Fries $1.25");
int choice = input.nextInt();
switch (choice){
case 1: mcChicken *= tax;
case 2: fries *= tax;
}
}
public void location() {
//Don't know what's supposed to go in here.
//But I've implemented the method as I was supposed to.
}
}
Does it all make sense is basically what i'm asking.
What should go in the location method?
What's the use of getters and setters within this class and did I do it right?
1) Your constructor is structured fine, but you should use Strings instead of chars for the name and location. A char will only hold one character.
2) You can create multiple instances of a class:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
McDonalds location2 = new McDonalds("McDonald2", "Kirkman", false);
3) You should add the tax to the price as a percentage, not a sum: price * 1.06. Be careful not to change the price w/o tax when you print the total price.
Name and location should be String not char.
I like the style of calling setters from within the constructor, because its a form of code reuse, especially if there are special checks being made on those values, such as not being null - calling he setter means you only check this in one place.
Your code won't compile, but you're close:
McDonalds location1 = new McDonalds("Some name", "Kirkman", true);
Your calculation is a little off too:
double tax = 0.06;
totalPrice *= (tax + 1);
However, this is dangerous because if called twice, it will add the tax twice. It would be better to have a method return the tax included price which calculates it every time. Having a getter with side effects is a design error. Ie have thus:
public double getTaxIncPrice() {
double tax = 0.06;
return totalPrice * (1 + tax);
}
In addition to the problem that Bohemian pointed out (name and location should be String, not char):
Your constructor call will need quotes on the String parameters:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
and your tax calculation is incorrect - you will need to multiply the total amount by the tax percentage, and you will have to wait until you actually have a total to do the calculation.
Just editted my code and provided the question. Your guys inputs helped so far.
public String TacoBellSauce(String fire, String hot, String mild) {
System.out.println("What sauce would you like to have?");
System.out.println("1. Fire");
System.out.println("2. Hot");
System.out.println("3. Mild");
int choice = input.nextInt();
switch(choice) {
case 1:
return fire;
case 2:
return hot;
case 3:
return mild;
}
return null;
}
Here is also my method for the TacoBell class. How would I return it in the Test class? It says to make a method within TacoBell that returns a string of what hot sauce I would like. But then it says within the test class to call hotsauce and return hot. I haven't created that class yet cause I'm focused on correcting everything with McDonalds and TacoBell.

java simple neural network setup

I have decided to play around with some simple concepts involving neural networks in Java, and in adapting somewhat useless code I found on a forum, I have been able to create a very simple model for the typical beginner's XOR simulation:
public class MainApp {
public static void main (String [] args) {
Neuron xor = new Neuron(0.5f);
Neuron left = new Neuron(1.5f);
Neuron right = new Neuron(0.5f);
left.setWeight(-1.0f);
right.setWeight(1.0f);
xor.connect(left, right);
for (String val : args) {
Neuron op = new Neuron(0.0f);
op.setWeight(Boolean.parseBoolean(val));
left.connect(op);
right.connect(op);
}
xor.fire();
System.out.println("Result: " + xor.isFired());
}
}
public class Neuron {
private ArrayList inputs;
private float weight;
private float threshhold;
private boolean fired;
public Neuron (float t) {
threshhold = t;
fired = false;
inputs = new ArrayList();
}
public void connect (Neuron ... ns) {
for (Neuron n : ns) inputs.add(n);
}
public void setWeight (float newWeight) {
weight = newWeight;
}
public void setWeight (boolean newWeight) {
weight = newWeight ? 1.0f : 0.0f;
}
public float getWeight () {
return weight;
}
public float fire () {
if (inputs.size() > 0) {
float totalWeight = 0.0f;
for (Neuron n : inputs) {
n.fire();
totalWeight += (n.isFired()) ? n.getWeight() : 0.0f;
}
fired = totalWeight > threshhold;
return totalWeight;
}
else if (weight != 0.0f) {
fired = weight > threshhold;
return weight;
}
else {
return 0.0f;
}
}
public boolean isFired () {
return fired;
}
}
In my main class, I've created the simple simulation in modeling Jeff Heaton's diagram:
However, I wanted to ensure my implementation for the Neuron class is correct..I've already tested all possible inputs ( [true true], [true false], [false true], [false false]), and they all passed my manual verification. Additionally, since this program accepts the inputs as arguments, it also seems to pass manual verification for inputs such as [true false false], [true true false], etc..
But conceptually speaking, would this implementation be correct? Or how can I improve upon it before I start further development and research into this topic?
Thank you!
It looks like a good starting point. I do have a few suggestions:
For scalability, fire() should be restructured so that a neuron that's already fired with the current input set doesn't have to recalculate each time. This would be the case if you had another hidden layer, or more than one output node.
Consider splitting your threshold calc into its own method. Then you can subclass Neuron and use different types of activation functions (bipolar sigmoid, RBF, linear, etc).
To learn more complex functions, add a bias input to each neuron. It's basically like another input with it's own weight value, but the input is always fixed at 1 (or -1).
Don't forget to allow for training methods. Backpropagation will need something like the inverse of fire(), to take a target output and ripple the weight changes through each layer.
From the (limited) work I've done with neural nets, that implementation and model looks correct to me - the output is what I'd expect and the source looks solid.

Categories

Resources