How to create a addline method? - java

I am having issues with my assignment about adding a new line using the below lines 1 through 4, as instances of InvoiceLine class into my Invoice class.
Instance Variables:
Line1: a variable of type InvoiceLine class
Line2: a variable of type InvoiceLine class.
Line3: a variable of type InvoiceLine class.
Line4: a variable of type InvoiceLine class.
addLine is a method that takes the following four input parameters: item number, item description, item price, and quantity.
The method then adds a line to the invoice only if the invoice has less than four lines. If the invoice already has four lines, then this method should print an error message.
How would I do it to make it work properly? I would appreciate any help.
Invoice Class:
public class Invoice {
// Instance Variables
private String customerName;
private int numItems;
private InvoiceLine line1;
private InvoiceLine line2;
private InvoiceLine line3;
private InvoiceLine line4;
// Contructors
public Invoice(){}
public Invoice(String customerNam){
customerName = customerNam;
}
//Getters
public String getCustomerName(){
return customerName;
}
//Setters
private void setCustomerName(String customerNam){
customerName = customerNam;
}
public void addLine(int itemNum, String Description, double itemPrice, int quantity){
if (numItems <= 4) {
numItems += line1;
if (numItems <= 4)
numItems += line2;
if (numItems <= 4)
numItems += line3;
if (numItems <= 4)
numItems += line4;
}
if (numItems == 4){
System.out.print("Error");
}
}
public double getInvoiceTotal(){
numItems *= numItems;
return numItems;
}
public String toString(){
String invoiceOutput = "";
invoiceOutput += (customerName + " brought "+ numItems);
return invoiceOutput;
}
}
InvoiceLine Class:
public class InvoiceLine {
//Instance Variables
private Item itemSold;
private int quantity;
public double total = 0;
// Constructors
public InvoiceLine(){}
public InvoiceLine(Item itemSold, int quantity){
this.itemSold = itemSold;
this.quantity = quantity;
}
public InvoiceLine(int itemNum, String itemDescription, double itemPrice, int quantity){
this.itemSold = new Item(itemNum, itemDescription, itemPrice);
this.quantity = quantity;
}
//Getters
public Item getItemSold() {
return itemSold;
}
public int getQuantity(){
return quantity;
}
//Setters
private void setItemSold(Item itemSold){
this.itemSold = itemSold;
}
private void setQuantity(int quantity){
this.quantity = quantity;
}
// Methods
public double getLineTotal(double total){
total = (quantity * itemSold.getItemPrice());
return total;
}
public String toString(){
String invoiceLine = "";
invoiceLine = (itemSold + " brought "+ quantity + ", which the total cost is "+ total);
return invoiceLine;
}
}

Looks like you will want to go back through your addLine method. Based on the description you provided for this method (which I assume is from your assignment), it sounds like this method should just set one of your InvoiceLine instance variables for that Invoice. I don't want to just write the solution for you as this is for an assignment so the point is to learn from doing! But here are some tips for where to focus:
Pay attention to the instance variable types in your Invoice class. You are trying to "add" these to your numItems variable, which has type int. This wont work well!
You shouldn't need to worry about checking the numItems value more than once in the addLines method. Once you check it and see it is less than 4, you know you should have available lines to add!
If you are adding lines, you need to be creating some new InvoiceLines. Take a look at one of your constructors for that class. You should see one of those would work well for the parameters you are given in the addLine method.
One important thing I'll point out though that should help you avoid more tedious hiccups: you are going to want to initialize your numItems variable to 0! You can either do this in the constructors or just set its default value in its declaration, like so: private int numItems = 0;.
Then, remember you have to increment/decrement this variable in your methods whenever a line is added or removed, it's not automatic. So the last thing you will want to do in your addLine method is numItems++. But only if everything was added successfully! (In otherwords, if the method wasn't actually able to add a line because there were already 4, you don't want to increment the numItems).
Hope that helps point you in the right direction! I'd give it another shot and see how far you get. If you run into other specific issues you can't figure out, feel free to comment.

Related

How Can I calculate the difference of age between 2 objects?

I am learning JAVA OOP, I have to compare the age between 2 objects:
In java Procedural, I will have done:
public static int calculateDifferenceAge(int agePlayer1, int agePlayer2){
int differenceAge = agePlayer1 - agePlayer2;
if(differenceAge < 0){
differenceAge = -differenceAge;
}
return differenceAge;
}
Then
public static void displayDifferenceAge(String namePlayer1, String namePlayer2, int agePlayer1, int agePlayer2){
System.out.println("Age difference between " + namePlayer1 + " and " + namePlayer2 + " is of" + calculateDifferenceAge(agePlayer1, agePlayer2) + " year(s).");
}
}
I don't understand how to create my calculateDifferenceAge() method in OOP ?
In my main file I have this:
List<Player> players = new ArrayList <Player>();
players.add(new Player("Eric", 31, true));
players.add(new Player("Juliette", 27, false));
I am stuck into my 2 methods:
How to subtract the age of 2 objects?
public static int calculateAgeDifference(List <Player> players){
Player differenceAge = (players.get(0) - players.get(1));
return differenceAge;
}
public static void displayCalculateAgeDifference(List <Player> players){
System.out.println(calculateAgeDifference().age);
}
Class Player
public class Player {
public String name;
public int age;
public boolean sex;
public Player(String name, int age, boolean sex){
this.name = name;
this.age = age;
this.sex = sex;
}
you're only missing a little step in your code. The steps to extract the ages of the list should be:
1.- Extract the object from the list
2.- Extract the age of that object (or player, in this case)
3.- Substract the ages
There's some ways to do it, but I would do it this way:
public static int calculateAgeDifference(List<Player> players) {
int age1= players.get(0).age;
int age2= players.get(1).age;
int differenceAge = age1 - age2;
if(differenceAge < 0){
differenceAge = -differenceAge;
}
return differenceAge;
}
I hope that helps. What i've done there is extract the objects player from the list: players.get(0) extracts the first object inside the list, which is a Player. Now that I have a player and it has an age variable i have to extract it with player.age. I collapsed those steps, if you have any questions I can explain you further
Display method:
public static int displayCalculateAgeDifference (List<Player> players){
String name1= players.get(0).name;
String name2= players.get(1).name;
//as you know this method return the difference in a number form
int difference= calculateAgeDifference(players);
System.out.println("Age difference between " + name1 + " and " + name2 + " is of" + difference + " year(s).");
}
Let's start with a class Player. Let's give it a name and an age, and a calculateAgeDifference method. It should look something like,
public class Player {
private int age;
private String name;
public Player(String name, int age) {
this.name = name;
this.age = age;
}
public int calculateAgeDifference(Player player2) {
return Math.abs(this.age - player2.age);
}
}
Then you can call it like
Player a = new Player("Eric", 40);
Player b = new Player("Sally", 51);
System.out.println(a.calculateAgeDifference(b));
You must have a similar Player class. Yours appears to also have a boolean field. It isn't clear why. So I can't speak to that.
Why did your method interface change from two parameters to a list? You can still pass two instances of the object. You can still return the integer age value from the method, no need to create a Frankenstein's Player instance only to hold the age.
I am assuming your Player class has a method getAge() to extract the age value which was passed in in the constructor:
public static int calcAgeDiff(final Player player1, final Player player2) {
int age1 = player1.getAge();
int age2 = player2.getAge();
return Math.abs(age2 - age1);
}
Alternatively, you can add an instance method to your Player class itself to calculate the age difference to a different player:
public class Player {
// fields
// constructor
// getters
public int ageDiffTo(final Player otherPlayer) {
return Math.abs(this.age - otherPlayer.age); // <- a class can always access its private fields, even of other instances
}
}
then call as player1.ageDiffTo(player2)

A way to get a variable in a method from a constructor in the same class?

I'm very new at code, and I can't find an explanation or solution that I can understand even though I'm pretty sure this is simple. I hope I got the terms right too. What I'm confused about is:
public class Item{
public Item(int number1, int number2, int number3){
//Nothing really significant in here, just some mathematics
}
public int getNumber(){
//I want to get the values of number 1-3 here, without parameters
//or any data structures if possible.^
}
}
If anyone could please explain it to me, I would be grateful. I would've looked up more, but I spent already half a day around these kind of problems and I'm not exactly experienced.
Thank you!
If you want to be able to retrieve a value at some point, you have to store it somewhere. This is done at the initialization phase when you create a new object with the constructor. When you call a constructor, you need to store the values you need when building your object. By doing that, your object keeps the needed values number1, number2, number3. Note that if you need to store an indefinite number of numbers that are not semantically defined (eg. you only store numbers that are not an area, a price, a quantity defined by a given name) then you should maybe store them inside an array.
public class Item {
private int number1; // internal attributes
private int number2; // are initialized
private int number3; // in the constructor
public Item(int number1, int number2, int number3) { // constructor
this.number1 = number1;
this.number2 = number2; // setup internal attributes
this.number3 = number3;
}
}
Then, when calling a getter, you may fetch the stored values. Your class has now 3 new functions.
public class Item {
private final int number1;
private final int number2;
private final int number3;
public Item(int number1, int number2, int number3){
this.number1 = number1;
this.number2 = number2;
this.number3 = number3;
}
// add getter methods that only return internal attributes
// values, so that it would be impossible to modify them
// from the outside
public int getNumber1() {
return number1; // equivalent of return this.number1;
}
public int getNumber2() {
return number2;
}
public int getNumber3() {
return number3;
}
}
Hope this solves your problem.
In constructor you can initialize class's variables. These variables belong to the class' instance, so the're available in the class' method. Each object that you create with new Item(1,2,4) will have it's own set of these fields.
To get each variable, it's better to use getters.
public class Item {
private final int number1;
private final int number2;
private final int number3;
// Method with same name as class called Constructor
public Item(int number1, int number2, int number3){
this.number1 = number1;
this.number2 = number2;
this.number3 = number3;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public int getNumber3() {
return number3;
}
}
You cannot really get 3 integers in 1 integer without any data structures. Think it in a way you wanna fit 3 sim cards in your phone with 1 slot.
also the function is named getNumber() which raises the question which number?
Same as the others said you will need to store your parameters in your class in some form so you will reuse them later
So you should use something like int[] or List<Integer> or even better a custom class named for example Numbers with methods getNumber1 getNumber2 getNumber3.
Hope that helped!
When you call Item(...) you need to save the parameters in the class properties, so that you can access them later when you call getNumber()
public class Item{
private int number1;
private int number2;
private int number3;
public Item(int number1, int number2, int number3){
this.number1 = number1;
this.number1 = number2;
this.number1 = number3;
//Nothing really significant in here, just some mathematics
}
public int getNumber(){
//here you can access to this.number1, this.number2, this.number3
}
}
check the snippet code :-
import java.util.*;
public class MyClass
{
public List<Integer> setNumberList = new ArrayList<Integer>();
public void setNumbers(int number1,int number2,int number3)
{
setNumberList.add(number1);
setNumberList.add(number2);
setNumberList.add(number3);
}
public List<Integer> getNumbers()
{
return setNumberList;
}
public static void main(String args[])
{
MyClass obj = new MyClass();
obj.setNumbers(9,2,3);
List<Integer> getyourNumbers= obj.getNumbers();
//the whole data is save in your list now you can get data by iterating it as you
want
System.out.print(getyourNumbers);
}
}

How to write GetItemIndex method

I am creating a ShoppingCart class that represents a shopping cart. I am good with the basics of the class and the getTotalPrice method, but I cannot figure out how to do the getItemIndex problem...
"Complete the getItemIndex method as follow: if the itemList has an item with the name passed into the parameter, return the index of that item in the array. Otherwise return -1. "
I know i have to call the Items class, but I do not understand how I can get the name from the item class and return the index.
I have created the Items class and the instance variables and constructor of the ShoppingCart class. I have looked at other shopping Cart methods, but I could not find one that does the getItemIndex
i Tried the code included in the bottom called getItemIndex... I included the getTotalPrice in case it is needed as a reference.
public class ShoppingCart{
private Items[] itemList;
//TODO: declare the number of distinct items in the cart
private int numItems = 0;
private static final int INITIAL_CAP = 5; // the initial size of the
cart
private static final int GROW_BY=3;
// ---------------------------------------------------------
// Creates an empty shopping cart with a capacity for 5 items.
// ---------------------------------------------------------
public ShoppingCart(){
itemList = new Items[INITIAL_CAP];
numItems = 0;
}
public double getTotalPrice(){
double totalPrice = 0;
numItems = 0;
for(int i = 0; i<itemList.length; i++){
if(itemList[i]!= null){
totalPrice = totalPrice + (itemList[i].getQuantity()*itemList[i].getPrice());
numItems++;
}
}
return totalPrice;
}
private int getItemIndex(){
if(itemList(itemList.getName))
return Items[itemList.getName];
else
return -1;
}
}
Here is the items class
public class Items{
private String name;
private double price;
private int quantity;
public Items (String n, double p, int q){
name = n;
price = p;
quantity = q;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public int getQuantity(){
return quantity;
}
public void addQuantity(int amt){
int newQuantity = amt + quantity;
quantity = newQuantity;
}
public String toString(){
return "item name: " + name + ", item quantity: " + quantity + ", total price: " + (price * quantity);
}
}
I expect a method that is an if statement, but I am not sure how to get the ItemIndex...I am not sure if this requires a for loop either. In another class, I will call this method to use it to simulate a shopping experience.
This should works. You specify nameOfItem you are trying to find. Then iterate through all items in array, if its in array, returns index.
int getItemIndex(String nameOfItem){
for(int i = 0; i < itemList.length; i++){
if(itemList[i].getName().equals(nameOfItem){
return i;
}
}
return -1;
}

Java Code Questions

I want to implement a class which includes a student's name, their GPA, grade level, and their final score. We had to create a Tester along with the initial class creates 2 different students, prints their grade level, GPA, their name, and the calculated final test score.
Formula to calculate final test score = .60 * written + .40 * handsOn
Any help would be appreciated, I can't get this program down and I've been trying for quite a while now.
Here is my code:
Tester:
public class IntroToJavaTester
{
public static void main()
{
IntroToJava j1 = new IntroToJava("Joe", 11, 3.2);
System.out.println(j1.getName());
System.out.println(j1.getGradeLevel());
System.out.println(j1.getGPA());
System.out.println(j1.getFinalScore(written, handsOn));
IntroToJava j2 = new IntroToJava("Jim", 11, 3.2);
System.out.println(j2.getName());
System.out.println(j2.getGradeLevel());
System.out.println(j2.getGPA());
System.out.println(j2.getFinalScore( written,handsOn));
}
}
Here is the IntroToJava class:
public class IntroToJava
{
private String name;
private int glev;
private double gpa;
private double finalscore;
private double written = 80;
private double handsOn = 90;
public IntroToJava(String a, int b, double c, double d, double e)
{
name = a;
glev = b;
gpa = c;
written = d;
handsOn = e;
}
public String getName()
{
return name;
}
public int getGradeLevel()
{
return glev;
}
public double getGPA ()
{
return gpa;
}
public double getFinalScore(int written, int handsOn)
{
finalscore = .60*written+.40*handsOn;
return finalscore;
}
}
Your IntroToJava constructor is defined with 5 arguments and you're calling it with only 3 in IntroToJavaTester.
The two arguments you're omitting appear to correspond to the fields written and handsOn.
You've defined getFinalScore to take two arguments with the same names but a different type.
I suspect what you probably really want is for getFinalScore to take no arguments but use these two fields.
Or perhaps getFinalScore is supposed to just be a getter for the field finalScore which doesn't seem to be set or used anywhere, but has a suspiciously similar name.

Using for loop for an ArrayLIst in Java (Blue J)?

Basically I've been having difficulty using a for loop to find the largest magnitude of an earthquake stored in an arraylist in class observatory. I get an error telling me that the variable "i" in my for loop cannot be found for the method to find the largest magnitude recorded by the observatory.
class Observatory
{
private String name;
private String country;
private int yearStarted;
private int area;
private int runningTotal;
private ArrayList<Earthquake> earthquakes;
private ArrayList<String> observatories;
Scanner userInput = newScanner(System.in);
private double largestMag(ArrayList<Earthquake> earthquake, double magnitude)
{
if (earthquake == null || earthquake.isEmpty()){
return 0;
}
for (Earthquake quake : earthquake) {
if (earthquake.get(0) < earthquake.get(i)){
return earthquake.get(i);
}
if (earthquake.get(0) > earthquake.get(i)){
return earthquake.get(0);
}
}
}
I know its something to do with the fact that in my earthquake class you add the earthquakes the array list is storing more than one piece of information?
this is my earthquake class
public class Earthquake
{
// instance variables - replace the example below with your own
private double magnitude;
private double latitude;
private double longitude;
private int yearOfEvent;
private String position;
private String details;
public Earthquake()
{
magnitude = 0;
latitude = 0;
longitude = 0;
yearOfEvent = 0;
}
public void setMagnitude(double magnitude)
{
this.magnitude= magnitude;
}
public double getMagnitude()
{
return magnitude;
}
public void setYear(int yearOfEvent)
{
this.yearOfEvent = yearOfEvent;
}
public int getYear()
{
return yearOfEvent;
}
public void setPosition(double latitude, double longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
public String getPosition()
{
position = latitude + ", " + longitude;
return position;
}
public String getDetails()
{
details = magnitude + " ," + latitude + "," + longitude + ","+ yearOfEvent;
return details;
}
}
I'm not sure how to get round the problem of pulling out the magnitude from the array list to use for calculations in my method. thanks.
You're mixing the ways to access the items in a List. Using the enhanced for loop like you have eliminates the counter variable that you'd have if you counted manually. Instead, you use the quake variable, which gets set to each value sequentially:
Earthquake largest = quakes.get(0); // start with whatever's first
for(Earthquake quake: earthquakes) {
if(quake.getMagnitude() > largest.getMagnitude()) {
largest = quake;
}
}
There are a few other issues as well:
Use just List instead of ArrayList for method parameters. This lets the person using your code send any kind of List over.
You can't compare objects using < and >. You can, however, implement the Comparable interface and provide a compareTo() method that will tell you which earthquake has a larger magnitude. Then you can just use Collections.max(earthquakes).
I don't know what you were trying to do in your loop logic, but you can't just return the first thing you see. If you need to perform a sequential search, you have a variable for "largest value so far" or "smallest value so far" and look at each item, updating the variable if you find a new extreme.
the for loop you have used internally uses an iterator, it doesn't have a counter variable i. Instead of using earthquake.get(i), use quake

Categories