I'm learning java at the moment and I've got a question about an object that got initialized and got a variable changed during the program execution.
public class Char {
private String name;
private int skill;
private int defense;
private int life;
private Weapon weapon = Weapon.FISTS;
private Potion potion = null;
So, I want this code to get the initial value of life that got initialized, but how would I access it?
public boolean isWeak() {
return life < this.life * 0.25;
}
So, this method is located in the Char class. I'm trying to get it to return a true value when it gets lower than 25%.
while (hero.isAlive() && monster.isAlive()) {
if (hero.isWeak() && hero.hasPotion()) {
hero.sip();
} else if (monster.isWeak() && monster.hasPotion()){
monster.sip();
} else {
System.out.println(monster.isWeak());
hero.attack(monster);
if (monster.isAlive()) {
monster.attack(hero);
}
System.out.println();
}
}
Here is the execution program. All the other methods work just fine, but as pointed out, it'll never return true because it can't be a quarter of itself. Don't mind the prints, I'm just testing it.
To do this, you need to create a second variable that stores the value passed into the constructor:
public class Char {
private String name;
private int skill;
private int defense;
private int initialLife;
private int life;
private Weapon weapon = Weapon.FISTS;
private Potion potion = null;
public Char(int initialLife //I am excluding all the other parameters you want to pass in
) {
this.life = initialLife;
this.initialLife = initialLife;
}
public boolean isWeak() {
return life < this.initialLife * 0.25;
}
}
As you can see, I store the initial life and I don't ever modify it. Since I modify the life variable, I can't use it to keep track of the initial value. Modifying a variable is a destructive process, and Java doesn't have a way to keep track of the history of variable values (unless you do it yourself as shown above).
Im having an issue where I have to create a method in java to get a ticket number which every time it is called it generates a number sequentially.
this is what I have so far regarding the ticket method
public class Ticket
{
public static final String PREFIX = "CAR";
public static int number = 1000;
//instance variables
private String ticketNumber;
public Ticket(){
ticketNumber = generateTicketNumber();
}
public String getTicketNumber(){
return ticketNumber;
}
private String generateTicketNumber(){
number = number++;
ticketNumber = PREFIX +number;
return ticketNumber;
}
I'm told to use a static variable (which i have) to create and hold a counter to generate part of the ticket number, increment the static variable and assign it combined with the string prefix to the field ticketNumber. When i create an object it does not increment to CAR1001, it just goes CAR1000, am I to try a while loop for this?
number = number++; is not evaluated how you think. What this actually does is that the right-hand side increments number, but number++ is also an expression whose value is the old value of number, before the increment is done. Then because of the number = ... assignment, that old value is assigned to number on the left-hand side, undoing the increment.
So you should just write number++; instead, which simply increments the variable.
Unless I'm missing something, I think you've over complicated this. All you need is PREFIX and number. Concatenate PREFIX with number and increment number. That can be done in one step like,
public class Ticket {
private static final String PREFIX = "CAR";
private static int number = 1000;
public String getTicketNumber() {
return PREFIX + number++;
}
}
Or, perhaps a little easier to read,
public String getTicketNumber() {
try {
return PREFIX + number;
} finally {
number++;
}
}
I have a class say Student
public class Student {
private String name;
private int score;
}
Assume I have all getter/setters.
Currently, I have an object of the student class say std which is having score value as 50.
I want to add 10 to the score in this object.
I can do this by below code:
std.setScore(std.getScore() + 10);
I am looking for an elegant way to write the same in which I don't use both getter and setter and can just increment the score by 10 or even by 1.
Say by using ++ or something like +=10 etc.
Write a method:
public void incrementScore(int amount) {
score += amount;
}
Is a negative increment allowed? If not, check it:
/**
* Increments the score by the given amount.
*
* #param amount the amount to increment the score by; must not be negative
* #throws IllegalArgumentException if the amount is negative
*/
public void incrementScore(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("The increment must not be negative.");
}
score += amount;
}
This approach is more elegant than using get/set because:
it allows you to check the argument agains business rules,
it adds a business method with a name that reveals intention.
it allows you to write JavaDoc comments that describe the exact behaviour of the operation
As sugested in the comments you can create a new method on the student class.
public class Student {
private String name;
private int score;
public void incrementScore(int increment){
this.score = this.score + increment;
}
}
And then call it on the std instance:
std.incrementScore(10)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm looking for some tip on how to do a percentage thing for my game I want all flowers in a range of 1-98 and white/black flowers 99-100 to make it more rarerity thanks for the help :)
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1 ),
RED_FLOWERS("red", ":red:", "470419583250202644", 1),
RAINBOW_FLOWERS("rainbow", ":rainbow:", "470419602841665536", 1),
PASTEL_FLOWERS("pastel", ":pastel:", "470419629450199040", 1),
ORANGE_FLOWERS("orange", ":orange:", "470419647900942366", 1),
BLUE_FLOWERS("blue", ":blue:", "470419688753594368", 1),
BLACK_FLOWERS("black", ":black:", "470419706751352842", 1);
private final String displayName;
private final String emoticon;
private int value;
private final String id;
FlowerSuit(String displayName, String emoticon, String id, int value ) {
this.displayName = displayName;
this.emoticon = emoticon;
this.value = value;
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public String getEmoticon() {
return emoticon;
}
public String getId() {
return id;
}
public int getValue() {
// TODO Auto-generated method stub
return value;
}
}
This is how I'd do it, but it can probably be improved, for starters by using Java 8 streams etc.
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1,3),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1,2),
RED_FLOWERS("red", ":red:", "470419583250202644", 1,2),
RAINBOW_FLOWERS("rainbow", ":rainbow:", "470419602841665536", 1,2),
PASTEL_FLOWERS("pastel", ":pastel:", "470419629450199040", 1,2),
ORANGE_FLOWERS("orange", ":orange:", "470419647900942366", 1,2),
BLUE_FLOWERS("blue", ":blue:", "470419688753594368", 1,2),
BLACK_FLOWERS("black", ":black:", "470419706751352842", 1,1);
private static Random random = new Random();
private final String displayName;
private final String emoticon;
private int value;
private final String id;
private final int freq;
private FlowerSuit(String displayName, String emoticon, String id, int value, int freq ) {
this.displayName = displayName;
this.emoticon = emoticon;
this.value = value;
this.id = id;
this.freq = freq;
}
public String getDisplayName() {return displayName;}
public String getEmoticon() {return emoticon;}
public String getId() {return id;}
public int getValue() {return value;}
/**
* Choose a flower
* white has a 3 in 16 (about a 5:1) chance of being picked
* Black has a 1 in 16 chance, everything else 2/16
* #return
*/
public static FlowerSuit pick() {
//first sum all the chances (currently it's 16)
int sum = 0;
for (FlowerSuit f:FlowerSuit.values()) sum+= f.freq;
//now choose a random number
int r = FlowerSuit.random.nextInt(sum) + 1;
//now find out which flower to pick
sum = 0;
for (FlowerSuit f:FlowerSuit.values()) {
sum += f.freq;
if (r<=sum) return f;
}
//code will never get here
return FlowerSuit.WHITE_FLOWERS;
}
public static void main(final String[] args) throws Exception {
//Test it
Map<FlowerSuit,Integer>count = new HashMap<FlowerSuit,Integer>();
for (int a=0;a<1000000;a++) {
FlowerSuit f = FlowerSuit.pick();
Integer i = (count.get(f)!=null)?count.get(f):new Integer(0);
i = new Integer(i+1);
count.put(f,i);
}
int sum = 0;
for (Map.Entry<FlowerSuit,Integer>e:count.entrySet()) sum+=e.getValue();
float f = Float.valueOf(sum);
for (Map.Entry<FlowerSuit,Integer>e:count.entrySet()) {
System.out.println(e.getKey() + " was chosen " + ((e.getValue() / f) * 100f) + "% of the time");
}
}
}
gives
BLUE_FLOWERS was chosen 12.4986% of the time
PASTEL_FLOWERS was chosen 12.4707% of the time
WHITE_FLOWERS was chosen 18.7365% of the time
BLACK_FLOWERS was chosen 6.2632003% of the time
ORANGE_FLOWERS was chosen 12.4986% of the time
RED_FLOWERS was chosen 12.5241995% of the time
YELLOW_FLOWERS was chosen 12.501401% of the time
RAINBOW_FLOWERS was chosen 12.5068% of the time
You can use a TreeMap to map all of the integers from 0 to 99 to a particular FlowerSuit. Take advantage of the floorEntry method to choose a FlowerSuit for each number. It might look something like this.
public class FlowerChooser {
private static final NavigableMap<Integer, FlowerSuit> FLOWER_SUITS;
private static final Random RANDOMS = new Random();
public FlowerChooser() {
FLOWER_SUITS = new TreeMap<>();
FLOWER_SUITS.put(0, FlowerSuit.RED_FLOWERS);
FLOWER_SUITS.put(14, FlowerSuit.ORANGE_FLOWERS);
FLOWER_SUITS.put(28, FlowerSuit.YELLOW_FLOWERS);
FLOWER_SUITS.put(42, FlowerSuit.GREEN_FLOWERS);
FLOWER_SUITS.put(56, FlowerSuit.BLUE_FLOWERS);
FLOWER_SUITS.put(70, FlowerSuit.INDIGO_FLOWERS);
FLOWER_SUITS.put(84, FlowerSuit.VIOLET_FLOWERS);
FLOWER_SUITS.put(98, FlowerSuit.WHITE_FLOWERS);
FLOWER_SUITS.put(99, FlowerSuit.BLACK_FLOWERS);
}
public FlowerSuit randomFlowerSuit() {
int index = RANDOMS.nextInt(100);
return FLOWER_SUITS.floorEntry(index).getValue();
}
}
Create just one object of this class, then whenever you want a FlowerSuit, call the randomFlowerSuit method.
The randomFlowerSuit method picks a random number from 0 to 99, then finds an appropriate entry in the map. The floorEntry method chooses an entry whose key is less than or equal to the chosen number. This means that numbers from 0 to 13 get mapped to red, 14 to 27 get mapped to orange, and so on. The only number that gets mapped to white is 98, and the only number that gets mapped to black is 99.
No matter what solution you implement, you want to include a frequency measure in your enum. As an example, you can do something like this:
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1, 1),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1, 20),
// More declarations here
// Add this variable
private final int frequency;
// Do just as you did before in the constructor, but with the frequency
FlowerSuit(String displayName, String emoticon, String id, int value, int frequency){
this.frequency = frequency;
// More assignments here
}
public int getFrequency(){
return frequency;
}
// More getters here
}
This addition is critical, and no matter what method you use to weight flower selection, you will want this addition to your FlowerSuit enum.
Now, we can explore a few different ways to perform this selection.
Note 1: I use ThreadLocalRandom for random numbers in a range, which is from java.util.concurrent.ThreadLocalRandom.
Note 2: For each of these, make a single instance of FlowerPicker, and use the pickFlower() method to pick the next flower. This avoid running costly setup code over and over.
Method 1: Bag of Flowers
This method is probably the easiest to implement. It entails creating a list of enums where each is represented frequency times, and then selecting a random entry from this list. It is similar to throwing a bunch of flowers in a bag, shaking it, and then reaching your hand in and grabbing the first flower you touch. Here's the implementation:
public class FlowerPicker(){
private ArrayList<FlowerSuit> bag;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
// You can use an array here or an array list with a defined length if you know the total of the frequencies
bag = new ArrayList<FlowerSuit>();
// Add each flower from options frequency times
for (FlowerSuit flower : options)
for (int i=0; i<flower.getFrequency(); i++)
bag.add(flower);
}
public FlowerBag pickFlower(){
// Now, select a random flower from this list
int randomIndex = ThreadLocalRandom.current().nextInt(0, bag.size());
return bag.get(randomIndex);
}
}
This method has the advantage of being simple enough to understand very easily. However, it can be inefficient if your frequencies are extremely specific (like if you want a rainbow flower to be returned 499,999,999 times out of 1,000,000,000). Let's move on to the next method.
Note 1: You could make this better by reducing the fractions representing the frequency of being chosen, but I'll leave this to you.
Note 2: You could also make this slightly better by storing identification numbers, not FlowerSuit objects in the bag list.
Method 2: Navigable Map
This method is a little bit more difficult. It uses a [NavigableMap][1], which is an implementation of [TreeMap][2]. This method is fairly similar to the Bag of Flowers method, but it is a little bit more efficient. Put simply, it uses the TreeMap to give each FlowerSuit a range of numbers that can be selected to return that FlowerSuit. Here's a full example:
public class FlowerPicker(){
private NavigableMap<Double, FlowerSuit> map;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
map = new TreeMap<Double, FlowerSuit>();
int runningTotal = 0;
// Add each flower with the proper range
for (FlowerSuit flower : options){
runningTotal += flower.getFrequency();
map.put(runningTotal, flower);
}
}
public FlowerBag pickFlower(){
// Now, select a random number and get the flower with this number in its range
int randomRange = ThreadLocalRandom.current().nextInt(0, bag.size());
return map.higherEntry(randomRange).getValue();
}
}
This is a solid method, and it scales well for very specific frequencies. If you have a bunch of different types of flowers, it will be slightly worse, but this method is still a good option at large scales. There's one more option though.
Method 3: Enumerated Distribution
This method is really nice because you barely have to do anything. However, it uses [EnumeratedDistribution][3] from Apache Commons. Enumerated Distribution requires a list of pairs of objects and weights. Anyway, lets jump into it:
public class FlowerPicker(){
private EnumeratedDistribution distribution;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
List<Pair<FlowerSuit, Double>> weights = new List<Pair<FlowerSuit, Double>>();
// Add each flower and weight to the list
for (FlowerSuit flower : options){
weights.add(new Pair(flower, flower.getFrequency()));
// Construct the actual distribution
distribution = new EnumeratedDistribution(weights);
}
public FlowerBag pickFlower(){
// Now, sample the distribution
return distribution.sample();
}
}
This is my favorite method, simply because so much of it is done for you. Many problems like this have been solved, so why not use solutions that always exist? However, there is some value to writing the solution yourself.
In conclusion, each of these methods are perfectly fine to use at your scale, but I would recommend the second or third method.
My teacher gave me confusing instructions on this coding assignment. If you guys could help elaborate or give me tips, I'll provide what I have.
First of all the program is where I have to make 2 classes that will work with a big class to produce a shopping list where you can edit how much of each item you want. Have to take the name of an item, how many times its purchased, and how much each one costs.
I finished my first class, I'll post the entire coding and rules for the coding at the bottom of this question.
Okay so here's what I have. I'll go step by step.
Rule 1: A field private Purchase[] as an array of purchases.
Another int field that tracks how many purchases have actually been made
So I made this:
private int Purchase[];
private int purchaseCount;
Rule 2: Negative values do not make sense, so just reset those to zero if provided by user
Okay so in the first program I had to do the same thing, but I'm confused how to do it now.
I implemented the "reset to zero" in the modifiers, but now my teacher is not asking for modifiers. Am I supposed to put them anyway? I know I just have to put an "if blahblahblah < 0, then blahblahblah = 0" thing, but how do I go about that?
Rule 3: Accessor .length() method that returns your int field for how many purchases
public int Purchase(){
return ;
}
I guess this is about all I know for that. I know I have to return something, not sure how to use length though. And I think there's a parameter.
Final Rule 4: Accessor .get(int) for the Purchase array, which needs a parameter that will index the array. So get(0) returns the first element (a Purchase object) of the array.
I think I understand this, but since I don't know how to do the last step, I haven't tried this yet. ".get(int)" what? So an accessor where I perform a .get(int) inside it? I don't know much about accessors, this is why I need this help. The rest of the program seems pretty simple for me, but this initial stuff confuses me. Thanks.
Rules for already completed class:
Three fields, a String for name of the purchase, int for units purchased, and a double for cost per unit.
• Standard accessors and modifier methods for each field.
• Negative values are not allowed, so change those to zero in all cases.
• Constructor to initialize these three fields (String, int, double) in that order.
• Constructor overload, (String, double) assumes the int quantity is zero.
• Default constructor that assumes name is “” and numbers are zero, must call the three argument constructor.
• A getCost method that is simply the number of units purchased times unit price.
• A toString method return a String with the item name followed by the unit price in parentheses
Completed program:
public class Purchase {
private String purchase;
private int unitsPurchased;
private double costPerUnit;
// Accessors
public String purchase() {
return purchase;
}
public int unitsPurchased() {
return unitsPurchased;
}
public double costPerUnit() {
return costPerUnit;
}
// Modifiers
public void setPurchase(String purchase) {
this.purchase = purchase;
}
public void setunitsPurchased(int unitsPurchased) {
if (unitsPurchased < 0) {
unitsPurchased = 0;
}
this.unitsPurchased = unitsPurchased;
}
public void setCostPerUnit(double costPerUnit) {
if (costPerUnit < 0) {
costPerUnit = 0;
}
this.costPerUnit = costPerUnit;
}
//constructors
public Purchase() {
this("", 0, 0);
}
public Purchase(String initialPurchase, double initialCostPerUnit) {
this.purchase = initialPurchase;
this.unitsPurchased = 0;
this.costPerUnit = initialCostPerUnit;
}
public Purchase(String initialPurchase, int initialUnitsPurchased, double initialCostPerUnit) {
this.purchase = initialPurchase;
this.unitsPurchased = initialUnitsPurchased;
this.costPerUnit = initialCostPerUnit;
}
//end of everything I am sure about
//beginning of unsurety
public static double getCost(String purchase, int unitsPurchased, double costPerUnit) {
return unitsPurchased * costPerUnit;
}
public static String toString(String purchase, int unitsPurchased, double costPerUnit){
return purchase + costPerUnit;
}
}
Okay, so first rule 1 the code should look like:
private Purchase[] purchases;
private int purchaseCount;
Remember, in this case since you've already defined Purchase in your other java file, you're using it as a datatype, not as an identifier.
For rule 2, you're going to want that if statement in the access methods for purchaseCount as well as in the constructor.
Rule 3 is extremely vague...but my best guess is your teacher wants you to define a length method for that class, so that when you call say purchases.length() it returns the purchase count.
Again, rule 4 is vague, but my best guess is you need to define a get method for that class that just returns a value from your private purchases array using a given index.
Something like this:
public Purchase get(int index) {
return purchases[index]
}
I hope this helps and good luck!!