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;
}
Related
The toString() method will return a String that includes all of the items in the purchases array, organized by category. toString() will also include the total cost of the order before taxes, the tax amount, the total amount (before tax + tax) and the number of items ordered. The number of items ordered is determined by the quantity field and is not the same as the number of items stored in the purchases array (numPurchases).
Here is my code:
import java.text.NumberFormat;
public class Receipt {
private Item[] purchases;
private int numPurchases;
public Receipt(int capacity) {
purchases = new Item[capacity];
numPurchases = 0;
}
public void add(Item itm) {
purchases[numPurchases] = itm;
numPurchases++;
}
public double totalBeforeTax() {
double total =0;
for (int i = 0; i < numPurchases; i++) {
total += purchases[i].getQty()*purchases[i].getPrice();
}
return total;
}
//WORK ON THIS!
public double totalTax() {
return totalBeforeTax();
}
public String toString() {
StringBuilder info = new StringBuilder();
//Append the Format the Table of Item
info.append(String.format("%-15s","Item")).append("\n");
info.append("---------------------------------------------------").append("\n");
//Display Items inside the toString
for (int i = 0; i < numPurchases; i++) {
info.append(purchases[i]).append("\n");
}
//Append the Before Tax, Tax, Total, and Number of Items
info.append("---------------------------------------------------").append("\n");
info.append("Before Tax: ").append(NumberFormat.getCurrencyInstance().format(totalBeforeTax())).append("\n");
info.append("Tax: ").append(NumberFormat.getCurrencyInstance().format(totalTax())).append("\n");
info.append("Total: ").append(NumberFormat.getCurrencyInstance().format(totalBeforeTax()+totalTax())).append("\n");
//WORK ON THIS!
info.append("Number of items: " + purchases[numPurchases]);
return info.toString();
}
}
You are given a list of n products, each with a name, price and weight.
Find out how many duplicates of a product are present within the list. A duplicate is a product with all parameters, equal to some other product.
input is 3 lists
Name Price Weight
1. ball 2 1
2. box 2 2
3. ball 2 1
4. ball 2 1
5. box 2 3
output:
2
explanation:
(1.) is same as (3.) and is also same as (4.) so there is 2... 1->3 and 1->4
Function Description
numDuplicates has the following parameter(s):
name: string array of size n, where names[i] denotes the name of the ith product
price: int array of size n, where prices[i] denotes the price of the ith product
weight: int array of size n, where weights[i] denotes the weight of the ith product
function you need to fill out:
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
// Write your code here
//return an int
}
this is what i wrote for my code and is O(n^2) but some test-cases are running out of time so i think it wants an O(n) solution but i cant think of it...
class Result {
/*
* Complete the 'numDuplicates' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. STRING_ARRAY name
* 2. INTEGER_ARRAY price
* 3. INTEGER_ARRAY weight
*/
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
int count = 0;
List<obj> classList = new ArrayList<obj>();
for(int i=0; i<name.size(); i++){
obj holder = new obj(name.get(i),price.get(i),weight.get(i));
classList.add(holder);
}
for(int i=0; i<classList.size(); i++){
for(int j=i+1; j<classList.size();j++){
if(classList.get(i).isDuplicate(classList.get(j))){
count++;
classList.remove(classList.get(j));
j--;
}
}
}
return count;
}
}
class obj{
String name;
int price;
int weight;
public obj(String name, int price, int weight){
this.name = name;
this.price = price;
this.weight = weight;
}
public boolean isDuplicate(obj x){
if(this.name.equals(x.name) && this.price == x.price && this.weight == x.weight){
return true;
}
return false;
}
}
i created my own object class, and i created a compare method but i think it might be inefficent
For :
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
// Write your code here
//return an int
}
Use Like below:
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
List<String> f1 = new ArrayList<String>();
int countTotal = name.size();
for (int i = 0; i < countTotal; i++) {
f1.add(name.get(i) + price.get(i) + weight.get(i));
}
//Unique List item
Set<String> uniqueItemSet = new HashSet<String>(f1);
Integer uniqueItems = uniqueItemSet.size();
int countAll = f1.size();
return(countAll-uniqueItems);
}
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
Set<String> uniqueProducts = new HashSet<String>();
for (int i = 0; i < name.size(); i++)
uniqueProducts.add(name.get(i) + " " + price.get(i) + " " + weight.get(i));
return name.size() - uniqueProducts.size();
}
public static int numDuplicates(List<String> names, List<Integer> price,
List<Integer> weight) {
int count = 0;
String product = "";
Map<String, Integer> dupMap = new HashMap<String, Integer>();
for (int i = 0; i < names.size(); i++) {
product = names.get(i) + price.get(i) + weight.get(i);
if (dupMap.get(product) != null) {
count++;
} else {
dupMap.put(product, 1);
}
}
return count;
}
List<string> final = new List<string>();
int countTotal = name.Count;
for (int i = 0; i < countTotal; i++) {
final.Add(name.ElementAt(i) + price.ElementAt(i) + weight.ElementAt(i));
}
var uniqueItems = final.Distinct();
int countDistinct = uniqueItems.Count();
return(countTotal-countDistinct);
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
int res=0;
HashSet<String> set = new HashSet<String>();
for(int i=0;i<name.size();i++){
String cmb = name.get(i) + "_" + price.get(i)+ "_" + weight.get(i);
if(set.contains(cmb)){
res++;
}
else{
set.add(cmb);
}
}
return res;
}
}
Or you may put the values in a pandas dataframe, then take the length of that data frame, use drop_duplicate function on to the dataframe to drop duplicates, take the revised dataframe's length, and then calculate the difference in length and print.
I have three class Homework that has my main(...), GradeArray, which has my methods, and StudentGrade, which has my constructor.
Currently , which is clearly wrong, I have in Homework:
GradeArray grades = new GradeArray();`
In GradeArray at the top I have StudentGrade[] ArrayGrades = new StudentGrade[size]; however this method did not give me both the contructor and the methods. I know I don't need three classes for this but my professor wants three class. How do I declare an array that has attributes from two classes so that I can get the methods from GradeArray and the constructor from StudentGrade?
Thank you for you time and help.
Here is all of my code
package homework1;
public class Homework1
{
public static int pubSize;
public static String pubCourseID;
public static void makeVarsPub(int maxSize, String courseID) //this is to makes the varibles public
{
pubSize = maxSize;
pubCourseID = courseID;
}
public int giveSize()
{
return pubSize;
}
public static void main(String[] args)
{
int maxSize = 100;
String courseID = "CS116";
//this is to makes the varibles public
makeVarsPub(maxSize, courseID);
StudentGrade grades = new StudentGrade();
grades.insert("Evans", 78, courseID);
grades.insert("Smith", 77, courseID);
grades.insert("Yee", 83, courseID);
grades.insert("Adams", 63, courseID);
grades.insert("Hashimoto", 91, courseID);
grades.insert("Stimson", 89, courseID);
grades.insert("Velasquez", 72, courseID);
grades.insert("Lamarque", 74, courseID);
grades.insert("Vang", 52, courseID);
grades.insert("Creswell", 88, courseID);
// print grade summary: course ID, average, how many A, B, C, D and Fs
System.out.println(grades);
String searchKey = "Stimson"; // search for item
String found = grades.find(searchKey);
if (found != null) {
System.out.print("Found ");
System.out.print(found);
}
else
System.out.println("Can't find " + searchKey);
// Find average and standard deviation
System.out.println("Grade Average: " + grades.avg());
System.out.println("Standard dev; " + grades.std());
// Show student grades sorted by name and sorted by grade
grades.reportGrades(); // sorted by name
grades.reportGradesSorted(); // sorted by grade
System.out.println("Deleting Smith, Yee, and Creswell");
grades.delete("Smith"); // delete 3 items
grades.delete("Yee");
grades.delete("Creswell");
System.out.println(grades); // display the course summary again
}//end of Main
}//end of homework1
package homework1;
class GradeArray
{
int nElems = 0; //keeping track of the number of entires in the array.
Homework1 homework1InfoCall = new Homework1(); //this is so I can get the information I need.
int size = homework1InfoCall.giveSize();
StudentGrade[] ArrayGrades = new StudentGrade[size];
public String ToString(String name, int score, String courseID)
{
String res = "Name: " + name + "\n";
res += "Score: " + score + "\n";
res += "CourseID " + courseID + "\n";
return res;
}
public String getName(int num) //returns name based on array location.
{
return ArrayGrades[num].name;
}
public double getScore(int num) //returns score based on array location.
{
return ArrayGrades[num].score;
}
public void insert(String name, double score, String courseID) //part of the insert method is going to be
//taken from lab one and modified to fit the need.
{
if(nElems == size){
System.out.println("Array is full");
System.out.println("Please delete an Item before trying to add more");
System.out.println("");
}
else{
ArrayGrades[nElems].name = name;
ArrayGrades[nElems].score = score;
ArrayGrades[nElems].courseID = courseID;
nElems++; // increment the number of elements
};
}
public void delete(String name) //code partly taken from lab1
{
int j;
for(j=0; j<nElems; j++) // look for it
if( name == ArrayGrades[j].name)
break;
if(j>nElems) // can't find it
{
System.out.println("Item not found");
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
boolean go = true;
if ((k+2)>size)
go = false;
if(go)
ArrayGrades[k] = ArrayGrades[k+1];
}
nElems--; // decrement size
System.out.println("success");
}
}
public String find (String name){ //code partly taken from lab1
int j;
for(j=0; j<nElems; j++) // for each element,
if(ArrayGrades[j].name == name) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return ArrayGrades[j].toString();
}
public double avg() //this is to get the average
{
double total = 0;
for(int j=0; j<nElems; j++)
total += ArrayGrades[j].score;
total /= nElems;
return total;
}
public double std() //this is to get the standard deviation. Information on Standard deviation derived from
//https://stackoverflow.com/questions/18390548/how-to-calculate-standard-deviation-using-java
{
double mean = 0; //this is to hold the mean
double newSum = 0;
for(int j=0; j < ArrayGrades.length; j++) //this is to get the mean.
mean =+ ArrayGrades[j].score;
for(int i=0; i < ArrayGrades.length; i++) //this is to get the new sum.
newSum =+ (ArrayGrades[i].score - mean);
mean = newSum/ArrayGrades.length; //this is to get the final answer for the mean.
return mean;
}
public StudentGrade[] reportGrades() //this is grade sorted by name
{
int in,out;
char compair; //this is for compairsons.
StudentGrade temp; //this is to hold the orginal variable.
//for the first letter cycle
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(0);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(0) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
//this is for the second run.
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(1);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(1) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
return ArrayGrades;
}
public StudentGrade[] reportGradesSorted() //this is grades sorted by grades.
//this is grabbed from lab2 and repurposed.
{
int in,out;
double temp;
for(out=1; out<ArrayGrades.length; out++)
{
temp=ArrayGrades[out].score;
in=out;
while(in>0 && ArrayGrades[in-1].score>=temp)
{
ArrayGrades[in]= ArrayGrades[in-1];
in--;
}
ArrayGrades[in].score=temp;
}
return ArrayGrades;
} //end of GradeArray
package homework1;
public class StudentGrade extends GradeArray
{
public String name;
double score;
public String courseID;
public void StudentGrade (String name, double score, String courseID) //this is the constructor
{
this.name = name;
this.score = score;
this.courseID = courseID;
}
}//end of StudentGrade class.
First, I feel #Alexandr has the best answer. Talk with your professor.
Your question doesn't make it quite clear what you need. However, it sounds like basic understanding of inheritance and class construction would get you going on the right path. Each of the 3 classes will have a constructor that is unique to that type. Each of the 3 classes will have methods and data (members) unique to those types.
Below is just a quick example of what I threw together. I have strong concerns that my answer is actually what your professor is looking for however--it is not an object model I would suggest--just an example.
public class Homework {
private String student;
public Homework(String name) {
student = name;
}
public String getStudent() {
return student;
}
}
public class StudentGrade extends Homework {
private String grade;
public StudentGrade(String grade, String name) {
super(name);
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
public class HomeworkGrades {
public List<StudentGrade> getGrades() {
// this method isnt implemented but should
// be finished to return array of grades
}
}
Take a look and see if that helps you understand something about inheritance and class construction.
Hopefully you can infer a bit about inheritence (StudentGrade inherits -- in java extends -- from HomeWork) and class construction.
Thnx
Matt
I change the array creation in Homework1 to be StudentGrade grades = new StudentGrade(); and I added extends GradeArray to the StudentGrade class. it is now public class StudentGrade extends GradeArray.
I have a method in the Candy Class named pricePerHundredGrams and what it is supposed to do is multiply the variable price times 100.00 and divide that answer by the variable weightGrams, and finally return that result to the variable wammy. When the variable wammy is called for in the very 2nd last statement of this code, it is supposed to pass the answer to return result. And ultimately c1 and c2 should display that result as well...but I get NaN for "per hundred grams". What is wrong with my code?
public class whatever
{ public static void main (String[] args)
{
processCandies();
System.out.println("end of processing");
}
public static void processCandies()
{
Candy c1 = new Candy("Hershey", 145, 4.35, 233);
Candy c2 = new Candy("Milky Way", 390, 2.66, 126);
System.out.println(c1);
System.out.println(c2);
}
}
class Candy
{
private String name;
private int calories;
private double price;
private double weightGrams;
double wammy = pricePerHundredGrams(price, weightGrams);
/**
Constructor
#param name
#param calories
#param price
#param gram
*/
public Candy(String n, int cal, double p, double wG)
{
name = n;
calories = cal;
price = p;
weightGrams = wG;
}
public String getName()
{
return name;
}
public int getCalories()
{
return calories;
}
public double getPrice()
{
return price;
}
public double getWeightGrams()
{
return weightGrams;
}
public double pricePerHundredGrams(double price, double weightGrams)
{
return (price * 100.00) / weightGrams;
}
public String toString()
{
String result;
result = name + "\n" + calories + " calories\n" + weightGrams + " grams\n" + wammy + " per hundred grams\n";
return result;
}
}
You are initializing wammy with the result of pricePerHundredGrams, but price and weightGrams haven't been initialized yet, so they're both 0. For double arithmetic, 0 divided by 0 is NaN (it's indeterminate in math).
Initialize wammy after price and weightGrams have valid values in your constructor:
public Candy(String n, int cal, double p, double wG)
{
name = n;
calories = cal;
price = p;
weightGrams = wG;
// Initialize wammy here.
wammy = pricePerHundredGrams(price, weightGrams);
}
Additionally, since they are already instance variables, you don't need to pass price and weightGrams as parameters to pricePerHundredGrams.
I am trying to add items to my array list with an action listener on a pop up window. You can see the action listener here. The problem that I am now having is I do not know how to add the inputs to my array list. Part of this problem is that I need to set my item number to 1 higher than the highest in my list. My array list is named as such:
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
and the class for InventoryItem looks like this:
public class InventoryItem { //Delcare variables below
DecimalFormat formatted = new DecimalFormat("#,###.00");//set up decimal format for displaying 12.34 type values
String itemName;
int itemNumber;
public String getItemName() {
return itemName;
}
public int getItemNumber(){
return itemNumber;
}
int inStock;
double unitPrice;
double value;
double restockingFee;
double inventoryValue;
public InventoryItem(String itemName, int itemNumber, int inStock, double unitPrice) { //declare variables for this class
this.itemName = itemName;
this.itemNumber = itemNumber;
this.inStock = inStock;
this.unitPrice = unitPrice;
stockValue(); //call stock value
}
}
So my question is two parts. The first is how do I get my itemNumber to increment to 1 higher than the highest? Do I simply do a bubble sort to find the highest? And the second part is how do I get it to add all items, including this incremented itemNumber, into my original arraylist?
Note
If needed I can paste my code in it's entirety on pastebin as it is somewhat large.
EDIT: Per #Prabhakaran I have added some code and I am almost there. I have almost gotten this to work, however when I start to look through my list I do not see the added feature so how can I be sure that I am actually adding it?
String newItemName = String.valueOf(xField);
String text1 = yField.getText();
String newInventoryAmount = String.valueOf(text1);
int newNumber = Integer.parseInt(newInventoryAmount);
String text2 = zField.getText();
String newUnitPrice = String.valueOf(text2);
double newPrice = Double.parseDouble(newUnitPrice);
for (int i = 0; i >= inventory.size(); i++) {
inventory.get(inventory.size() ).getItemNumber();
int newItemNumber;
newItemNumber = i + 1;
InventoryItem item = new InventoryItem(newItemName, newItemNumber, newNumber, newPrice);
inventory.add(item);
What am I missing here? Shouldn't this simply add an item to my arraylist? I know it must be something really easy, I just can't seem to figure it out.
Here is my sort by ItemName:
static ArrayList sortInventory(ArrayList<InventoryItem> unsorted) {
ArrayList<InventoryItem> sorted = new ArrayList<>(); //create new array list to sort
InventoryItem alpha = null;
int lowestIndex = **-1**;
while (unsorted.size() > 0) { //while my unsorted array is less than 0 do the following
for (int i = 0; i < unsorted.size(); i++) { //increment through
if (alpha == null) {
alpha = unsorted.get(i); //get the next line in the inventoryItem array
lowestIndex = i;
} else if (unsorted.get(i).itemName.compareToIgnoreCase(alpha.itemName) < 0) { //compare items to determine which has a higher value
alpha = unsorted.get(i);
lowestIndex = i;
}
}
sorted.add(alpha); //reset the index so it will loop until there are no more items in the unsorted array
unsorted.remove(lowestIndex);
alpha = null;
lowestIndex = **0**;
}
return sorted; //return the sorted arraylist
}
EDIT: Corrected the lowestIndex and it goes good as gold.
Do like this
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
String newItemName = String.valueOf(xField);
String newInventoryNumber = String.valueOf(yField);
int newNumber = Integer.parseInt(newInventoryNumber);
String newUnitPrice = String.valueOf(zField);
double newPrice = Double.parseDouble(newUnitPrice);
InventoryItem item =new InventoryItem(newItemName , newInventoryNumber , newNumber , newUnitPrice ) ;
inventory.add(item);
update
class SimpleComparator implements Comparator<InventoryItem> {
#Override
public int compare(InventoryItem o1, InventoryItem o2) {
return new Integer(o1.getItemNumber()).compareTo(o2.getItemNumber());
}
}
//Sorting based on the itemNumber.
Collections.sort(inventory,new SimpleComparator());
int newItemNumber = inventory.get(inventory.size() - 1).getItemNumber();
newItemNumber ++;
You could create your own ArrayList with Observer support:
public class InventoryItemArrayList extends ArrayList {
private static final long serialVersionUID = 4550719458611714650L;
private List listeners = new ArrayList();
public void addInventoryItemAddedListener(InventoryItemAddedListener listener) {
this.listeners.add(listener);
}
#Override
public boolean add(InventoryItem e) {
boolean add = super.add(e);
fireInventoryItemAdded(e);
return add;
}
private void fireInventoryItemAdded(InventoryItem e) {
for (InventoryItemAddedListener element : listeners) {
element.inventoryItemAdd(e);
}
}
#Override
public void add(int index, InventoryItem element) {
super.add(index, element);
fireInventoryItemAdded(element);
}
#Override
public boolean addAll(Collection c) {
boolean addAll = super.addAll(c);
fireInventoryItemAdded(c);
return addAll;
}
private void fireInventoryItemAdded(Collection c) {
for (InventoryItem inventoryItem : c) {
fireInventoryItemAdded(inventoryItem);
}
}
#Override
public boolean addAll(int index, Collection c) {
boolean addAll = super.addAll(index, c);
fireInventoryItemAdded(c);
return addAll;
}
}