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)
Related
Please advise on where I am going wrong. Eclipse isn't showing an error but my answer is not correct.
The task is to write a method sales() that takes a single integer parameter representing the number of additional vacations of that type sold. The method should add this number to the totalSold instance variable and return nothing.
public void sales() {
int sales = 0;
sales = sales + totalSold;
}
You were supposed to add to totalSold (not sales), and you aren't passing sales into the method. Like,
public void sales(int sales) {
this.totalSold += sales; // <-- add sales to totalSold
}
Of course, that assumes you have already defined totalSold. Make sure you have that
private int totalSold = 0;
public void sales(int parameterName){
//your code
}
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!!
I'm writing a program that acts as a 'pocket' where the user is able to enter a kind of coin, such as, a quarter and the amount of quarters it has. I was assigned to do 3 different class, the Coin Class in which the coins and their values can be instatiated from, a Pocket Class, where I have to write a method that can add the coins of the user (basically the method would act like ArrayList .add() ) and the PocketClass tester. I have already written most of the code, but I am stuck as to how I could write the following method:
public void addCoin(String s, int i)
{
// s is type of coin, you are using s to instantiate a Coin and get value
// i is number of coins, you are using i to keep adding value to the totalValue
}
My question is how should I approach this? I am not quite clear on how to create method. Would I use a for-loop in order to keep track of the number of coins? I understand that the addCoin method works a lot like .add() from ArrayList.
Here is the code from my other classes:
public class Coin
{
private final String DOLLAR = "DOLLAR";
private final String QUARTER = "QUARTER";
private final String DIME = "DIME";
private final String NICKEL = "NICKEL";
private final String PENNY = "PENNY";
private int value;
private String coinName;
public Coin(String s,int count)//name of the coin and also the number of the coins you have
{
//Use if or switch statement to identify incoming string and provide value
double value=0;
if(DOLLAR.equalsIgnoreCase(s))
{
value=100.0;
}
else if(QUARTER.equalsIgnoreCase(s))
{
value=25.0;
}
else if(DIME.equalsIgnoreCase(s))
{
value=10.0;
}
else if(NICKEL.equalsIgnoreCase(s))
{
value=5.0;
}
else if(PENNY.equalsIgnoreCase(s))
{
value=1.0;
}
}
public int getValue()
{
return value;
}
}
and how the Pocket class is structured:
public class Pocket
{
private int currentValue;
private int totalValue;
private Coin quarter;
private Coin dime;
private Coin nickle;
private Coin penny;
public Pocket()
{ //Set initial value to zero
totalValue = 0;
currentValue = 0;
}
public void addCoin(String s, int i)
{
// s is type of coin, you are using s to instantiate a Coin and get value
// i is number of coins, you are using i to keep adding value to the totalValue
}
public int getValue()
{
return totalValue;
}
public void printTotal()
{
//print out two different output
}
}
I'm assuming you're adding the addCoin method in the Pocket class.
If you intend to keep track of the number of coins of each type within a Pocket, the simplest way to do so would be to declare a Hashmap that is keyed by the coin type (say, a "quarter" or a "dollar") and valued by the number of coins of that type. An invocation of the addCoin(type, count) method, say addCoin("dollar", 5) can then check if the hashmap already contains a key named "dollar" and if present, increment it's value by count.
I would suggest storing coins in a list so that you can add unlimited number of them.
Example:
class Coin{
//Same as your code....
public Coin(String coinType){
//..Same as your code, but removed number of coins
}
}
public class Pocket
{
private int currentValue;
private int totalValue;
//Create a list of coins to store unlimited number of coins
// A pocket can half 5 dimes
List coins;
public Pocket(){
//Set initial value to zero
totalValue = 0;
currentValue = 0;
coins = new ArrayList<Coin>();
}
/**
* This method will take only one coin at a time
**/
public void addCoin(String s){
Coin c = new Coin(s);
coins.add(c);
totalValue+=c.getValue();
}
/**
* This method will take any number of coins of same type
**/
public void addCoin(String s, int c){
//Add each one to array
for(int i=0;i<c;i++)[
addCoin(s);
}
}
}
I am not in favor of keeping multiple coin values in one Coin object because of the fact it is not a true representation of an object. What does that mean is tomorrow if you want to store other Coin attributes like "Printed Year", "President Picture on the coin" etc, you will have hard time. In my opinion it is better to represent one real world object (one coin here) using one object instance in the program,
I have 2 classes. 1 class sets & gets a students' name, 3 test scores for a student & an average for the 3 scores. The other class has a main method to set and get this information. I'm getting an error from my IDE for the 2nd class only.
public class Student5th
{ /**
Instance variables
Each student object will have a name and three test scores
*/
private String name; //Student name
private int test1; //Score on test 1
private int test2; //Score on test 2
private int test3; //Score on test 3
/**
Set a student's name
Preconditions -- nm is not empty
Postconditions -- name has been set to name
*/
public void setName (String nm)
{
name = nm;
}
/** Get a student's name
Preconditions -- none
Postconditions -- returns the name
*/
public String getName ()
{
return name;
}
/** Set the score on the indicated test
Preconditions -- 1 <= i <= 3
-- 0 <= score <= 100
Postconditions -- test i has been set to score
*/
public void setScore (int i, int score)
{
if (i == 1) test1 = score;
else if (i == 2) test2 = score;
else test3 = score;
}
/** Get the score on the indicated test
* Preconditions -- none
* Postconditions -- returns the score on test I
* */
public int getScore (int i)
{
if (i == 1) return test1;
else if (i == 2) return test2;
else return test3;
}
/** Compute and return a student's average
* Preconditions -- none
* Postconditions -- returns the average of the test scores
* */
public int getAverage() {
int average;
average = (int) Math.round((test1 + test2 + test3) / 3.0);
return average;
}
}
My 2nd class with the main method...
import java.util.*;
public class TestStudent
{
public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
private Student **student1**;
private Student **student2**;
String s;
int t;
student1 = new Student();
student2 = new Student();
s = console.next();
student1.setName (s);
t = console.nextInt();
student1.setScore (1, t);
student1.setScore (2, console.nextInt());
student1.setScore (3, console.nextInt());
student2.setName (**keyboard**.readLine());
student2.setScore (1, console.nextInt());
student2.setScore (2, console.nextInt());
student2.setScore (3, console.nextInt());
}
}
I've bolded (well, put double asterisks around) the parts which are giving me errors. I'm close to getting this program to work, but I don't know why my IDE is giving me problems for student1 & student2 in the 2nd class, as well as giving me a problem for (keyboard.readLine()); for student2.setName in the 2nd class?
You shouldn't specify an access level modifier (like private or public) inside a method:
Student student1; // delete 'private'
Student student2; // delete 'private'
Why? Because if you declare a variable inside a method, it should only be visible inside that specific method. It doesn't make sense to declare it as private, public or protected.
You could take a look to this article about Information hiding.
A few things going on here.
If your lecturer specified that student1 and student2 must be private, then he intended them to fields of the class. That means you have to declare them outside of the method. Move these two declarations up, to before the line that says public static void main ....
Also, your class is called Student5th, but you're using it within TestStudent as if it were just Student. The class name used in the variable declarations has to match the actual name of the class.
Where you wrote keyboard.readLine() towards the end, you actually meant to write ccnsole.nextLine(). You shouldn't be trying to read the same input stream with two different objects at the same time.
If you do change keyboard.readLine() to console.nextLine(), then you'll need an extra call to console.nextLine() immediately before it, to consume the newline character at the end of the line that has the first student's third score.
Could someone look at the portion of my code where I'm trying to void and close an account? This is what I want to achieve:
"2. Add a method void close() to your Account class. This method should close the current account by appending “CLOSED” to the account name and setting the balance to 0. (The account number should remain unchanged.) Also decrement the total number of accounts."
When I tried to compile it, the program gave me an error about an identifier being expected. What am I missing?
//*******************************************************/
// Account.java
//
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
//*******************************************************/
public class Account
{
private double balance;
private String name;
private long acctNum;
//----------------------------------------------
//Constructor -- initializes balance, owner, and account number
//----------------------------------------------
public Account(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//----------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}
//----------------
//Track how many accounts
//----------------
private static int numAccounts=0;
{
numAccounts++;
}
public static int getNumAccounts()
{
return numAccounts;
}
//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//----------------------------------------------
// Returns balance.
//----------------------------------------------
public double getBalance()
{
return balance;
}
//----------------------------------------------
// Returns account number.
//----------------------------------------------
public long getAcctNumber()
{
return acctNum;
}
//----------------
//Void and close the accounts
//----------------
public void close(Account)
{
balance = 0;
name = "CLOSE";
acctNum = number;
numAccounts--;
return Account;
}
//----------------------------------------------
// Returns a string containing the name, account number, and balance.
//----------------------------------------------
public String toString()
{
return "Name: " + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
public void close(Account) needs a variable name. The declaration says it takes an Account parameter, but you also need to give the parameter a name e.g. public void close(Account account).
Note that I don't think that makes much sense. Given an account object you should probably be able to close it, so perhaps you should reconsider whether that parameter makes sense.
There are few problems:
public void close(Account) << why do you have Account as a parameter (half parameter)?
{
balance = 0;
name = "CLOSE"; << This is assignment, not addition
acctNum = number; << where number came from
acctNum--;
return Account; << this is a void method, why do you return something?
}
It should look like that:
public void close()
{
balance = 0;
name += "CLOSE"; << adding "close" to current account name
acctNum--;
}
Another thing, acctNum is the total number of accounts, it shouldn't be related to a specific object, so it should be declared as static.
EDIT
Clarification regarding the account count and account number:
For each account, there should be an account number, let's say the first account has account number = 1 and the second account has account number = 2 etc. so we'll call this variable accountNumber and declare it as private variable:
private int accountNumber;
You also want to track the number of active accounts, right? So you create another variable which is not bounded to a specific account, but is related to all, and call it accountCount and you should declare it as static variable:
private static int accountCount = 0;
When you close an account, you want to decrease the account count and keep the count number, so your method should look like:
public void close()
{
balance = 0;
name += "CLOSE";
accountCount--; << we decrease the account count, not the specific account number
}
Would be best to go for
public void close() { ... }
you'd be calling it on an instance of the account class (like myAccount.close()) so it's going to be working on itself. Adding stuff you don't need is almost always a bad idea :)
You don't specify a parameter name.
Change it to
public void close(Account acct){
//...
}
public void close() {
...
}
I think they're expecting you to add a method with that signature.
Also, it says to append "CLOSED" to the name not "set" the name to "CLOSED".
I don't think you need to modify anything with the acctNum variable.
Those should be enough hints to complete this.
This line needs to be inside of a method rather than part of your class declaration:
{
numAccounts++;
}
Try making it:
public void incrementAccountNumber() {
numAccounts++;
}
You need to specify an argument name for your close() method:
public void close(Account account) { ... }
Further to the other answers, you've got an unknown variable number:
acctNum = number;
public void close(Account)
should have a variable name. Something like this:
public void close(Account account)
{
balance = 0;
name = "CLOSE";
acctNum = number;
acctNum--;
}