Methods & Parameters - java

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
}

Related

Elegant way to add a value to a class variable in java

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)

problems with ArrayList in if-statement and for-loop

I have a question regarding the for-loop and ArrayList. I have a HashMap with String and Integers, where the String represents a class, and the Integer represents the grade. They I have a collection of students in an ArrayList. So what I am trying to do is find the average of the grades of the students in the ArrayList. This is the code of that class:
import java.util.ArrayList;
public class BachelorStudenter {
private ArrayList<BachelorStudent> bs;
public Bachelorstudenter() {
bs = new ArrayList<>();
}
public int bsGjennomsnitt() {
int sum = 0;
int gjennomsnitt = 0;
if(!bs.isEmpty()){
for(BachelorStudent b : bs.values){
sum += b.finnGjennomsnitt();
}
return gjennomsnitt;
}else {
return 6;
}
}
}
I know that the bs.values in the for-loop within the if-statement is wrong, but I've tried googling what I should use instead, and neither .contains or .size works.
Oh, and I also have another class called BachelorStudent, where I can create an object of the BachelorStudent and it will be put in the ArrayList in Bachelorstudenter.
Does anyone know what I need to put there instead?
If what you want to to is to return the average of the average grade over all the students you could do the following:
import java.util.ArrayList;
public class Bachelorstudenter {
private ArrayList<Bachelorstudent> bs;
public Bachelorstudenter() {
bs = new ArrayList<>();
}
public double bsGjennomsnitt() {
double sum = 0.0;
double gjennomsnitt = 6.0;
if(!bs.isEmpty()){
for(Bachelorstudent b : bs){
sum += b.finnGjennomsnitt();
}
gjennomsnitt = sum/bs.size()
}
return gjennomsnitt;
}
}
please note that I changed the return value, sum and gjennomsnitt to double as an average may also be a non-integer value.
The answer also assumes that the b.finnGjennomsnitt() returns the average over all classes a student attends and returns this. If you only want to return the average for all students in ONE class the answer will not give you this. Please specify in your question and also include the code for finnGjennomsnitt() if this is part of the question.
The method in the answer will return 6.0 as average if there are no students, as in the code in the question. Perhaps this should be reconsidered as it makes the case of an exceptional group of students with straight 6.0 grades equal to the case of no students. Perhaps you can return -1 when there are no students?
What you a doing is recursively ending in an exception....
You have to do::
for(Bachelorstudent b : bs){
sum += b.getSomething();
}
and define getSomething as a getter for a field in the classs Bachelorstudent

Looping the wrong way?

The assignment for my class asks me to create a program that tells a supermarket which customer, on a daily basis, has spent the most money in the store. The program must find this customer and display their name.
Goals of assignment - To work with multiple classes, work with ArrayLists and apply the knowledge gained.
My question:
How should I loop my two output statements in my main class? Is that right in my main method? I need it to loop until the sentinel is used.
How is this going to affect my sentinel?
What type of questions should I be asking myself when dealing with loops? I'd like to think I'm overthinking this portion.
I really want to understand what I am doing here, so any help in the right direction would be appreciated! Thanks, in advance, for taking the time to help me out!
import java.util.Scanner;
public class main {
public static void main(String[] args) {
System.out.println("* * * * * THE SUPERMARKET * * * * *");
System.out.println(" Written by Nate Irwin");
System.out.println();
double finalTotal = -1;
String anAccountName;
Scanner input = new Scanner(System.in);
Store store = new Store();
do {
System.out.println("Enter the customer name: ");
if(input.hasNextLine()){
anAccountName = input.nextLine();
System.out.println("Enter customer total price, hit 0 to QUIT: ");
finalTotal = input.nextDouble();
store.addAccount(anAccountName, finalTotal);
System.out.println();
}
} while (finalTotal != 0);
System.out.println(store.getHighestCustomerTotal() + " has spent the most with us today!");
}
}
Store class:
import java.util.ArrayList;
public class Store {
// Creates an ArrayList.
private ArrayList<CustomerAccount> accounts = new ArrayList<CustomerAccount>();
//
public void addAccount(String anAccountName, double finalTotal) {
accounts.add(new CustomerAccount(anAccountName, finalTotal));
}
// Gets the HIGHEST customer total.
public String getHighestCustomerTotal() {
CustomerAccount highest = accounts.get(0);
for (int i = 1; i < accounts.size(); i++) {
if (accounts.get(i).getTotal() > highest.getTotal())
{
highest = accounts.get(i);
}
}
return highest.getAccountName();
}
}
CustomerAccount class:
public class CustomerAccount {
// Variables defined to this class.
private String accountName;
private double total;
// Constructor.
public CustomerAccount(String anAccountName, double finalTotal) {
accountName = anAccountName;
total = finalTotal;
}
// Gets total from each customer.
public double getTotal() {
return total;
}
// Gets a customer's name.
public String getAccountName() {
return accountName;
}
}
I think your approach is fine, it gets the job done.
I'm not too sure what you're asking by saying how should you loop the two output statements, followed by if it should be in the main method. From what I understand, and by looking at your code, running this input loop is perfectly fine from the main class. The do-while is fine although I'd move the first 'introductory' output outside the loop so you don't see it every time the loop reiterates.
Also, I notice you're not actually calling/instantiating the Store class in your main method, there's no data being added to the Store class for when it iterates through the accounts ArrayList.
As far as the answer that stated a more "modern" approach, I think the for loop you used is fine. I think the person was referring to the for-each loop. It doesn't really matter how you loop through it with the little amount of data you have.
There's some error in the logic for that loop. The getHighestCustomerTotal() is referencing an empty accounts ArrayList. You declared an ArrayList within the Store class and tried to loop through it but it's empty unless you called the addAccount() method from your main method at some point, so you'd need some error checking on that.
Your loop in main:
Doesn't really use the data you type in... One would expect this data to be used to create CustomerAccount instances
Has a completely unnecessary while(Condition) test at the end. This kind of loop is normally done with a While True and some test in the loop breaks out of the loop.
In getHighestCustomerTotal()
you can use a more "modern" form of the for() where you iterate elements of the list directly instead of iterating the index.

java: confusing instructions, shopping cart program

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!!

Can a static variable be updated by calling a method from another class in this circumstance? Java

Say, my Store class has this information...
public class Store {
private Product product1, product2, product3;
private static int productCount = 0;
public Store() {
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void setData(String name, int demand, double setup, double unit,
double inventory, double selling) {
if (productCount == 0) {
product1.setName(name);
product1.setDemand(demand);
product1.setSetUpCost(setup);
product1.setUnitCost(unit);
product1.setInvCost(inventory);
product1.setSellPrice(selling);
productCount = 1;
} else if (productCount == 1) {
product2.setName(name);
product2.setDemand(demand);
product2.setSetUpCost(setup);
product2.setUnitCost(unit);
product2.setInvCost(inventory);
product2.setSellPrice(selling);
productCount = 2;
} else if (productCount == 3) {
product3.setName(name);
product3.setDemand(demand);
product3.setSetUpCost(setup);
product3.setUnitCost(unit);
product3.setInvCost(inventory);
product3.setSellPrice(selling);
productCount = 3;
}
}
However, in my Interface class...
private void enterData() {
// Assume the user put in the required inputs here
Store.setData(name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice );
}
When I try to use this code, the productCount variable never changes from zero. Also, when I use another method to show product data, it never shows any information like name & so on (as though nothing was ever input). Something is wrong with how I'm trying to store this information.
I want to set data for only 3 products, but my program won't store any information. One guess of mine is that I can't statically try to address a non-static method to store product information. If so, I'm confused how I could store information for ONLY three products.
On top of that (assuming you can now store product information for 3 products), I want to ask the user if they would like to return to the main menu (a .run() method) or replace product information for one of the three products (which are now full) if they try to add information more than three times. I'm not sure how I could do this?
Thanks.
The code that you provided should not even compile.
You need something like:
public class YourInterfaceClass {
private Store store = new Store();
...
private void enterData() {
// Assume the user put in the required inputs here
store.setData(name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice );
}
}

Categories