Iterating through an arraylist of objects - java

I am working on a project that has a class called Items and a method called totals that calculates a grand total for an array of Items objects.
for some reason it cant see Items, I know that I am missing something simple or obvious but I just cant figure it out. Ant help would be appreciated.
public void totals(){
int index=0;
for (Iterator it = items.iterator(); it.hasNext();) {
Items i = it.next();
double itotal;
itotal = items.get(index).Items.getTotal();
}
}
and here is the Items class
public class Items {
public String name;//instance variable for item name
public int number;//instance variable for number of item
public double price;//instance variable for unit price
public double total;//instance variable for total
Items(String name,int number,double price){
this.name=name;
this.number=number;
this.price=price;
total=number*price;
}
public void setName(String name){
this.name=name;
}
public void setNumber(int number){
this.number=number;
}
public void setPrice(double price){
this.price=price;
}
public void setTotal(){
total=number*price;
}
public String getName(){
return name;
}
public int getNumber(){
return number;
}
public double getTotal(){
return total;
}
public double getPrice(){
return price;
}
Thanks in advance for the help.

Basically, there are two flaws:
you never increment the itotal variable and it's declared inside the loop
you never access the variable i in the current iteration
And also, shouldn't your totals method return something (like itotal)?
The way I see it, the proper way of iterating over that items array is
public double totals(){
double itotal = 0.0; //#A
for (Iterator<Items> it = items.iterator(); it.hasNext();) { //#B
Items i = it.next(); //#C
itotal += i.getTotal(); //#D
}
return itotal; //#E
}
Basically:
#A Here you initialize the itotal variable (outside of the loop) that will contain the grand total for all items
#B You start iterating over all items
#C You get the next item in the array
#D You increment the grand total with the current item's total
#E You return the grand total

There are a number of potential issues here.
In your for loop, you declare Items i, but never use it. Maybe it = it.next() should be a part of the for loop instead?
You call items.get(index), but index is always 0. You might want to use it here instead.
You declare double itotal and assign it within the for loop, so it's overwritten on each iteration. Maybe you want to declare it with an initial value outside the loop, and then increment it inside the loop.

Related

Java cycling through objects

I'm trying to cycle through objects and update a variable each time, I have a Player class that has all of the following variables:
Name, s1 ,s2, s3,...., s11, total
I want to go through each variable from the start to the end and adding the score at each go for each player (all the players are in an array list).
I'm not sure what the best way to do this is, is there a way to select a specific object and then add the variable depending on who go it is.
if you need any more information please ask and thanks in advance for any help given.
public void addScore(int turn, int score){
Player.setScore( turn, score);
}
You can cycle in array list with a simple for, like this:
ArrayList<Player> players = ...;
for (int i = 0; i < players.size(); i++) {
/*Operations on players[i] = the current player*/
}
To take and modify the variables of your player you can create getter and setter methods for each parameter like this:
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
If you have a lot of variables (s1, s11) of the same type, use an array:
int[] scores = new int[11];
So you can use another for cycle.
If I understand this question correctly, each player has a name, 11 scores, and a total. You seem to be asking how to iterate through a list of players and make the total equal to the sum of the 11 scores.
A more usual (in an OO language) approach would be just to ensure that the total is always equal to the sum of the 11 scores. (This is called "encapsulation", and is the fundamental idea behind all of object-oriented programming.) This is very easy to accomplish (for ease of programming, I put the scores in an array):
public class Player {
private String name ;
private int[] scores ;
private int total ;
public Player(String name) {
this.name = name ;
this.scores = new int[11] ; // all initialized to zero, as is total.
}
public void setScore(int whichScore, int score) {
int change = score - scores[whichScore] ;
scores[whichScore] = score ;
total = total + change ;
}
public int getScore(int whichScore) {
return scores[whichScore] ;
}
public int getTotal() {
return total ;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name ;
}
}
Now your question is redundant: the total is always equal to the sum of the scores, so there is no need to iterate through the players to compute the total anywhere in your code. You can get the total for each player with
for (Player p : listOfPlayers) {
System.out.println("Player "+p.getName()+" has total score "+p.getTotal());
}

What direction do I need to go in to complete this shopping cart assignment? [closed]

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 7 years ago.
Improve this question
So I'm basically completely lost in regards to where I'm supposed to go with this assignment. This is what the assignment is asking me to do.
"Part I:
Design a class named Item that has information about items that are for sale in a store. An Item has the following properties: Name, Vendor, Price, Weight, Taxable (a boolean field that indicates whether or not tax is charged on the item).
Part II:
Design a ShoppingCart class that contains items. Several interesting methods are
AddItem to insert an item to the cart.
CartTotal computes the total price of the cart.
CartTaxAmount receives the tax rate and computes the total tax to charge for the items currently in the cart. Only Taxable items should be considered for this calculation.
If it makes things easier, you can assume that the capacity of a ShoppingClass is fixed at 10 items.
Keep in mind:
Each class should have at least one constructor that receives arguments.
Make data members private and create accessor and mutator methods whenever necessary.
Each class should have a toString method that you use to display the contents of the class.
Write a standalone function that allows a user to enter information for an Item and returns an Item to the calling function.
"
I'm just not wrapping my head around how to store a class item in an array of another class.
import java.util.Scanner;
class Item {
//data members
private String Name;
private String Vendor;
private double Price;
private double Weight;
private boolean Taxable;
//constructor
Item(String conName, String conVendor, double conPrice, double conWeight, boolean Tax)
{
Name = conName;
Vendor = conVendor;
Price = conPrice;
Weight = conWeight;
Taxable = Tax;
}
//Aceessor methods
public String getname(){
return Name;
}
public String getvendor(){
return Vendor;
}
public double getprice(){
return Price;
}
public double getweight(){
return Weight;
}
public boolean gettaxable(){
return Taxable;
}
public String toString()
{
String s = "Item Name is " + Name + " and the vendor is " + Vendor + ". The Price of the item is " + Price + " and the weight of the item is " + Weight + ". Item is taxable = " + Taxable + ".";
return s;
}
}
public class ShoppingCart {
private Item[] itemsToBuy;
private double taxRate;
private int numItems;
ShoppingCart(int capacity, double taxamount) {
itemsToBuy = new Item[capacity];
taxRate = taxamount;
numItems = 0;
}
//Accessor methods
public double gettaxRate(){
return taxRate;
}
public int getItemNum() {
return numItems;
}
public Item getitemsToBuy(int i) {
return itemsToBuy[i];
}
//Methods
public void AddItem() {
}
Keep your head up; you're on the right track. You can pass an item to the AddItem method and then insert it in your itemsToBy array. You just have to check to make sure there's room in the cart.
Try this:
public void AddItem(Item item) {
if(numItems < itemsToBuy.length){
itemsToBuy[numItems] = item; //insert item in the array
numItems++; //increment the number of items
} else {
System.out.println("Your cart is full.");
}
}
Why don't you try to implement a removeLastItem() method that removes the newest item from the cart. This should help you practice.
I recommend you watch the Java for Complete Beginners videos at CaveofProgramming.com. They were very helpful when I first started learning Java.
I cannot give you a ready made answer since this is obviously a homework assignment that you are supposed to do. But here are a few pointers that will help you understand the problem more:
Item
You need to create a public class called Item. That would look similar to what you already have, except a few changes that you could make:
Make the class public (public class Item)
You don't need a big constructor like this. Since you have the mutator methods, you can keep you constructor default like the following:
public class Item {
public Item() {
// default constructor
}
...
}
Change your getters/setters to use the getXyz and setXyz forms for each private member xyz. Notice the uppercase X, followed by lowercase yz.
You don't need to print a statement in your toString() method; it will become long and will fill up your console with unnecessary text. Instead make it simple and concise. Also, make a practice of using StringBuilder to build a string instead of using string concatenation. While string concatenation is not necessarily bad, StringBuilder keeps it less controversial :)
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName()).append("\n")
.append("\t name: ").append(getName()).append("\n")
.append("\t vendor: ").append(getVendor()).append("\n");
// do the same for all fields
return sb.toString();
}
ShoppingCart
You will need a public class called ShoppingCart that would contain a List of Item objects; something like the following:
<pre>
import java.util.List;
import java.util.ArrayList;
public class ShoppingCart {
private final List<Item> items; // items can be of any size
private double taxRate;
public ShoppingCart() {
this.items = new ArrayList<Item>();
}
// getter for items List
public List<Item> getItems() {
return this.items;
}
// instead of a setter, we have an 'adder' which
// adds one element. you can call this method
// to add items one at a time to the items List
public void addItem(Item item) {
this.items.add(item);
}
// or you can use a varargs adder, using which
// you have the convenience of adding more than
// one item at a time
public void addItem(Item... items) {
if(items != null && items.length > 0) {
for(Item item : items) {
this.items.add(item);
}
}
}
// getter for taxRate
public double getTaxRate() {
return this.taxRate;
}
// setter for taxRate
public void setTaxRate(double taxRate) {
this.taxRate = taxRate < 0 ? 0 : taxRate;
}
// item count is calculated; it's not a field getter
public int getItemCount() {
return this.items.size();
}
// calculates total price without taxes
public double calculateCartPriceTotalNoTax() {
double total = 0.0;
for(Item item : this.items) {
total += item.getPrice();
}
return total;
}
// calculates total price with taxes
public double calculateCartPriceTotal() {
double totalNoTax = calculateCartPriceTotalNoTax();
double total = totalNoTax * getTaxRate() / 100;
return total;
}
// calculates total price with taxes (different way of doing it)
public double calculateCartPriceTotal2() {
double total = 0.0;
double taxRate = getTaxRate();
for(Item item : this.items) {
total += (item.getPrice() * getTaxRate() / 100);
}
return total;
}
// toString method for the ShoppingCart.
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName()).append("\n")
.append("\t items: ").append(getItems()).append("\n")
.append("\t taxRate: ").append(getTaxRate()).append("\n")
.append("\t totalPriceNoTax: ").append(calculateCartPriceTotalNoTax()).append("\n")
.append("\t totalPriceWithTax: ").append(calculateCartPriceTotal()).append("\n");
return sb.toString();
}
}
</pre>
Note:
May be you should start using Eclipse (or IntelliJ Idea, if you like). It will make writing Java code much easier, and will help you avoid many errors.

java - find the max value from a linked list

Disclaimer: I am a very early student and am struggling to learn java. Please tell me if I'm leaving out any important information.
I am writing a program that prompts the user to do various operations to a linked list (add, remove, change value, etc.) but rather than storing a string or some primitive data type I am storing objects of type Student (which basically contains a string for the name of the student and an integer for their test score) and am stuck on how to find the maximum test score since I can't just find the highest Student.
Any help would be appreciated.
Well you can have two variables, one as the currentScore, and another as the newScore. And then traverse through each student object, get the test value, and then compare. If the new score is lower, then keep current. If new score is higher, replace current score with new score, and keep traversing. When you traverse the list, you have the highest score
You can iterate over the list as other answers described or you can use Collections.max method. To use this method your Student class should implement comperable interface.
public class Student implements Comparable<Student>
and you need to add compareTo method to the class:
#Override
public int compareTo(Student student)
{
if (this.score > student.score)
{
return 1;
}
if (this.score < student.score)
{
return -1;
}
else
{
return 0;
}
}
Now when you write Collections.max(list) you will get the Student with the highest score.
I wrote a simple program that matched your case.
Main Class:
import java.util.*;
import java.lang.Math;
public class FindHighestScore
{
public static void main(String[] args)
{
LinkedList<Student> studentLinkedlist = new LinkedList<Student>();
studentLinkedlist.add(new Student("John",1)); // Adding 5 students for testing
studentLinkedlist.add(new Student("Jason",5));
studentLinkedlist.add(new Student("Myles",6));
studentLinkedlist.add(new Student("Peter",10)); // Peter has the highest score
studentLinkedlist.add(new Student("Kate",4));
int temp = 0; // To store the store temporary for compare purpose
int position = 0; // To store the position of the highest score student
for(int i = 0; i < studentLinkedlist.size(); i ++){
if(studentLinkedlist.get(i).getScore() > temp){
temp = studentLinkedlist.get(i).getScore();
position = i;
}
}
System.out.println("Highest score is: " + studentLinkedlist.get(position).getName());
System.out.println("Score: " + studentLinkedlist.get(position).getScore());
}
}
The student constructor class:
public class Student
{
String name;
int score;
Student(){
}
Student(String name, int score){
this.name = name;
this.score = score;
}
String getName(){
return this.name;
}
int getScore(){
return this.score;
}
}
The above program produce result as follows:
Highest score is: Peter
Score: 10

Having trouble adding together elements from array

I have to write a program that uses two classes to create a grocery list. The first class creates an array to hold the values gotten from the second class. The array holds grocery items which have a name, quantity, and price value. I have a function that is supposed to get a total cost of everything in the array, but for some reason the function is only adding the last item that is added to the array to itself. Here's my code:
public class GroceryList {
private GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
private int numofEntries;
public GroceryList()
{
this.groceryList = new GroceryItemOrder[10];
this.numofEntries = 0;
}
public void add(GroceryItemOrder item)
{
if(numofEntries == 10)
{
System.out.println("The list is full.");
}
else
{
groceryList[numofEntries] = item;
numofEntries++;
}
}
public double getTotalCost()
{
double totalCost = 0;
double newCost = 0;
for(int size = 0; size < numofEntries; size ++)
{
newCost = groceryList[size].getCost();
totalCost = newCost + totalCost;
}
return totalCost;
}
public class GroceryItemOrder {
private static double pricePerUnit;
private static int quantity;
private String name;
public GroceryItemOrder(String name, int quantity, double pricePerUnit)
{
this.name = name;
this.quantity = quantity;
this.pricePerUnit = pricePerUnit;
}
public static double getCost()
{
return (quantity * pricePerUnit);
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public static void main(String[] args)
{
GroceryList newList = new GroceryList();
newList.add(new GroceryItemOrder("cookies", 1, 1.50));
newList.add(new GroceryItemOrder("cheese", 2, 1.0));
newList.add(new GroceryItemOrder("bread", 1, 5.0));
System.out.println(newList.getTotalCost());
}
}
In the function I was trying to use a for loop that would run through the array one element at a time and take whatever values were stored into the element and store it into a new object. I feel like I'm heading in the right direction but can't figure out where the issue is with the function. Can anyone see where my issue is, or at least give me some advice on how I can begin to attempt to fix the issue?
2 of your 3 variables in GroceryItemOrder are static, which means only one variable for the entire class, not one for each instance. Each new instance overwrites the values set by the previously created instance.
Make all of those instance variables not static:
private double pricePerUnit;
private int quantity;
private String name;
The static modifier to quantity and pricePerUnit makes no sense if you want to have some variety in your grocery. What happens is that each time you call the constructor or GroceryItemOrder, you change those two static fields, so if affects the total price of all the previous orders created. The rest is fine even if it could be more concise sometimes.

Can't return the answer

The answer should be returned but it does not display for some reason. I have printed within for loop and seen that it's correct answer.
public class Salary
{
public static void main (String[]args)
{
double [] salary = {20000.00};
double riseRate = 1.07;
calculateSalary(salary, riseRate);
}
public static double [] calculateSalary(double [] salary, double riseRate)
{
for (int i=0; i<salary.length; i++)
{
salary [i] = salary [i] * riseRate;
}
return salary;
}
}
That's because you're not printing out the answer. Add a print statement in main.
System.out.println(calculateSalary(salary, riseRate)[0]);
You are returning an array. The salary is in the the first position of you array. If you want to see the salary you would need to use
return salary[0];
in your method.
or
System.out.println(calculateSalary(salary,riseRate)[0]);
in the main.
What you're trying to print right now is the actual array, not a value.
I am not sure why you are doing it like this, though.
Why not just use a double instead of double[]?

Categories

Resources