Shopping Cart - Array not storing a value - java

I have been trying to create a shopping cart where the user can enter the number of items he/she has purchased and the price for each item.
I am having problems with the array. I am not able to store the price for each product. How can I store the second value (the price) in an array to match each item?
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[][] itemsCart;
int itemsInTheCart=0;
int itemsPrice = 0;
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
for(int i = 0; i < itemsInTheCart; i++){
System.out.print("Enter the price for item " + (i+1) + ": ");
itemsPrice = scan.nextInt();
itemsCart = new int[itemsPrice][itemsPrice];
// System.out.println(itemsCart.length);
}
}

An array needs to be declared with its size before it can be used.
Also in your example you do not need a 2D array, a 1D array is fine.
Also you need to initialize your array outside the loop other wise it will get overridden in each iteration
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
int [] itemsCart = new int [itemsInTheCart];
for (....) {
itemsCart[i] = itemsPrice;
}

Instead Use ArrayList
for example create a object class
class ShoppingDetails{
private String itemName;
private Integer price;
public ShoppingDetails(String itemName, Integer price) {
this.itemName = itemName;
this.price = price;
}
//add getter and setter if you want
}
Now you can use the it in
ArrayList<ShoppingDetails> shoppingCart=new ArrayList<>();
shoppingCart.add(new ShoppingDetails("item1",100);
By this way you can map price to items.

As mentioned by #"Scary Wombat", your approach is better suited for a 1D array than a 2D one. However since you are looking to use a 2D array I would like to point your where you code could be better. Also mentioned by him to need to declare the size before using the 2D array
Your line "itemsCart = new int[itemsPrice][itemsPrice];" would be better as itemsCart = new int[i][itemsPrice]; as this will ensure that the new indexes are filled with the appropriate values.
I have made some edits to your main. Feel free to as me if you don't understand
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[][] itemsCart;
int itemsInTheCart=0;
int itemsPrice = 0;
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
itemsCart= new int[itemsInTheCart][2];
for(int i = 0; i < itemsInTheCart; i++){
System.out.print("Enter the price for item " + (i+1) + ": ");
itemsPrice = scan.nextInt();
itemsCart[i][1] = itemsPrice;
}
// for testing
for (int i=0;i<itemsInTheCart;i++){
System.out.println("Item: "+(i+1)+" for price: "+ itemsCart[i][1] );
}
}

import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int itemsInTheCart=0;
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
int[] itemsCart = new int[itemsInTheCart];
for(int i = 0; i < itemsInTheCart; i++){
System.out.print("Enter the price for item " + (i+1) + ": ");
itemsCart[i] = scan.nextInt();
}
for(int i = 0; i < itemsInTheCart; i++){
System.out.println(itemsCart[i]);
}
}
}

Related

How to create 4 arrays with one 2D array and how to scan them

I have to make a program about stores and sales. I have to read values from a costumer and put them in different arrays and the amount. The stores in one array, the product sold in other array and the amount of product and the price of all the products have to be in a 2d array.
I'm having struggles in that 2D array.
I've tried to read the values to all the array but when I print the 2D array it always gives me an error. I think that my problem is in "for" but I'm not sure because I'm new in java.
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int sells = 0;
String store = "";
System.out.print("How many sells did you make: ");
sells = read.nextInt();
String[] arrStores = new String[sells];
String[] arrProduct = new String[sells];
double[][] arrAmountPrice = new double[sells][2];
for (int i = 0; i < sells; i++) {
System.out.print("Store: ");
arrStores[i] = ler.next();
System.out.print("Product sold: ");
arrProduct[i] = ler.next();
System.out.print("Amount of product sold: ");
arrAmountPrice[i][0] = ler.nextDouble();
System.out.print("Price of all the product: ");
arrAmountPrice[i][1] = ler.nextDouble();
}
First you need to import 'java.util.Scanner' or 'java.util.*' classes in order to get access to the Scanner object, then all you need to do is replace your 'ler' objects with 'read'.
import java.util.*;
public class Test{
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int sells = 0;
String store = "";
System.out.print("How many sells did you make: ");
sells = read.nextInt();
String[] arrStores = new String[sells];
String[] arrProduct = new String[sells];
double[][] arrAmountPrice = new double[sells][2];
for (int i = 0; i < sells; i++) {
System.out.print("Store: ");
arrStores[i] = read.next();
System.out.print("Product sold: ");
arrProduct[i] = read.next();
System.out.print("Amount of product sold: ");
arrAmountPrice[i][0] = read.nextDouble();
System.out.print("Price of all the product: ");
arrAmountPrice[i][1] = read.nextDouble();
}
}
}

How to allow user to make edits to an array

I must create 3 arrays, one to hold 5 product IDs, one to hold 5 product prices, and one to hold 5 product inventories. I need a method to print all the product IDs, print all product prices, and print all the inventories. I need a method to allow user to make edits to any of the product IDs, product prices, or inventories (this is the method I am struggling with). After each edit is made I must reprint all the data. I also need a method to print all the correct data after all the edits are made and an extra column, the total price for each product and the overall price. Thanks in advance for any help!
import java.util.Scanner;
public class Inventory {
d public static void main(String[] args) {
String[] productIDArray = new String[5];
double[] priceArray = new double[5];
int[] inventoryArray = new int[5];
input(productIDArray, priceArray, inventoryArray);
print(productIDArray, priceArray, inventoryArray);
edit(productIDArray, priceArray, inventoryArray);
}
public static void input (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Enter the product ID, the price and inventory: ");
productIDArray[i] = input.next();
priceArray[i] = input.nextDouble();
inventoryArray[i] = input.nextInt();
}
}
public static void print (String[] productIDArray, double[] priceArray,
int[] inventoryArray) {
for (int i = 0; i < 5; i++) {
System.out.println(productIDArray[i]);
System.out.println(priceArray[i]);
System.out.println(inventoryArray[i]);
}
}
public static void edit (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
Scanner input = new Scanner(System.in);
int whatToEdit = 0;
String oldProductID = " ";
String newProductID = " ";
double oldPrice = 0;
double newPrice = 0;
int oldInventory = 0;
int newInventory = 0;
String yesNo = " ";
while (true) {
System.out.print("Do you want to make an edit? (Y/N)");
if (yesNo = y.toUppercase) {
System.out.print("Enter what you want to edit: ");
System.out.print("Do you want to edit a product ID (1), price (2), or
inventory (3)? ");
whatToEdit = input.nextInt();
if (whatToEdit == 1) {
System.out.print("Enter the product ID you want to edit and the edit: ");
productID = input.next();
newProductID = input.next();
productIDArray[product] = newProductID;
} else if (whatToEdit == 2) {
System.out.print("Enter the price you want to edit and the edit: ");
oldPrice = input.nextDouble();
newPrice = input.nextDouble();
priceArray[oldPrice] = newPrice;
} else if (whatToEdit == 3) {
System.out.print("Enter the inventory you want to edit and the edit: ");
oldInventory = input.nextInt();
newPrice = input.nextInt();
inventoryArray[oldInventory] = newInventory;
}
}
} else if (yesNo == n.toUppercase) {
break;
}
print(productIDArray, priceArray, inventoryArray);
}
public static void totalPrice (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
}
}
First check which array they want to edit. Then check which part of the array they want to change. You then just take the users input for which piece of the array and the new value for that piece.
Lets say they chose inventory array. Get input for which part of array and then the number to replace it with.
inventoryArray[usersinput] = //Users next inputted number they want to replace it with
EDIT:
To check which array they want to edit you could do something like this.
System.out.print("Enter 1 for product array, 2 for price array, and 3 for inventory: ");
Then read the users input again and use an if or switch statement to decide what to do with whichever array they chose.
EDIT 2:
Problems with your compare and toUppercase. I can't find where your defining the variable 'y' which you are using with your toUpperCase(). So you also need to define that somewhere.
if (yesNo.equals(y.toUppercase()))

double array won't print

I did some more work on this program, but now I am stuck because the string array prints, but i cant for the life of me get the double array to print. Any help would be appreciated!
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Double;
import java.util.Scanner;
public class inventoryTracker
{
private static Scanner sc;
private static double itemCost;
public static void main(String[] args)
{
System.out.println("Welcome to the Inventory tracker"
+ "\nThis program will accept the names and costs for 10 stocked items."
+ "\nThe program will then output a table with the names, costs and,"
+ "\nprices of the items."
+ "\nPrices are calculated with a 30 percent markup on cost.");
sc = new Scanner(System.in);
String[] product = new String[10];
Double[] itemCost = new Double[10];
for (int i = 0; i < itemCost.length; i++ ){
System.out.print("Enter the item cost :");
itemCost [i]= sc.nextDouble();
}
for (int i = 0; i < product.length; i++){
System.out.print("Enter the product name :");
product[i] = sc.next();
}
System.out.println(Arrays.toString(product));
}
}
That's because you are assigning a string to a string array in your two for loops.
product= sc.toString();
should be
product[i] = sc.toString();
and the same goes for itemCost.
That's because you are assigning a string to a string array in your two for loops. Also you are doing sc.toString() that is not correct.
product= sc.toString();
and
itemCost= sc.nextDouble();
should be changed to
product[i] = sc.nextLine();
and
itemCost[i] = sc.nextDouble();
and the same goes for itemCost.
You need to use index to set a value like:
product[index] = value;
Also you are using sc.toString() to get string from user. It wont work you need to use next() method to get string from user.
Loop should be like:
for (int i = 0; i < product.length; i++){
System.out.print("Enter the product name :");
product[i] = sc.next();
}
for (int i = 0; i < itemCost.length; i++ ){
System.out.print("Enter the item cost :");
itemCost [i]= sc.nextDouble();
}

Store/ Display Data Inputs from Arrays

I'm having problems on how and where to put arrays.
I figured out how and where to put a loop so it will keep on gathering multiple user data that will be stored inside the arrays but I don't know where to put arrays. There will be an array for product numbers, an array for product name, and an array for price.
import java.io.*;
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static void main(String args[])throws Exception
{
int y = 0;
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code =
Integer.parseInt(a.readLine());
System.out.println("");
if(code==l)
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices")
System.out.print("Enter product number:
") ;
int prodnum
Integer.parseInt(a.readLine());
System.out.println("")
}
if(code==3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}}}}
First of all, where do you get this l (lowercase L) value in your for loop? Shouldn't this be 1 (number one)? Furthermore, it would be even better if it is 0 (zero) so you can use it as an index for your array.
Second thing, what's the point of int y = 0'? You are not using y anywhere in your program.
int y = 0;
for(int x = l; x <= 100; x++)
Change it to:
for(int x = 0; x < 100; x++)
Since you want to have 3 separate arrays, you should have 3 separate indexes to keep track of them.
Now let's see how to initialize an array to store the data. You should declare the size as a variable at the top of your class (or locally in your main()) to make it easier to change it later across your program. You can do the same with your array. Declare it inside your class or locally inside the main(). I will show you how to declare both outside of the class, but you should try it the other way too for practice.
Now remember, when using arrays you have to know the size of the array in advance as soon as you create it and you cannot change that size after. This means only that many elements can fit inside the array. If you want variable size structures, check out some of the answers with ArrayLists.
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static int size = 100; // now you only change this number and everything works
public static int[] productNumbers = new int[size];
public static String[] productNames = new String[size];
public static int[] productPrices = new int[size];
public static void main(String args[]) throws Exception
{
int prodnumIndex = 0; // index for tracking product numbers
int prodnameIndex = 0; // index for tracking product names
int prodpriceIndex = 0; // index for tracking product prices
for(int x = 0; x < size; x++)
{
// ... your code...
// ...
int prodNum = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodnumIndex < productNumbers.length) {
productNumbers [prodnumIndex] = prodnum;
prodnumIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
String prodName = a.readLine();
// check if we didn't reach our maximum size
if(prodnameIndex < productNames.length) {
productNames [prodnameIndex] = prodName ;
prodnameIndex++; // increment
} else {
System.out.println("Cannot add product name. Reached maximum amount.");
}
// ...
int prodPrice = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodpriceIndex < productPrices.length) {
productPrices [prodpriceIndex] = prodPrice ;
prodpriceIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
}
Another way you can achieve this is to create an object called Product that will contain the properties you need and then have an array of that object.
class Product {
int num;
String name;
int price;
Product(int num, String name, int price) {
this.num = num;
this.name = name;
this.price = price;
}
}
// ...
// declare your array of `Product` objects...
Product[] products = new Product[size];
// ...
// then you can do something like
System.out.println("Enter product number:");
int prodNum = Integer.parseInt(a.readLine());
System.out.println("Enter product name:");
String prodName = a.readLine();
System.out.println("Enter product price:");
int prodPrice = Integer.parseInt(a.readLine());
products[INDEX] = new Product(prodNum, prodName, prodPrice);
// ...
Also, consider using a double of a float for the product price since it is more realistic representation of actual products.
Do you have to use an array and "if" statements?
Common practice is to use a List as switch statement:
int[] productArray = new int[100];
List<Integer> productList = new ArrayList<Integer>();
for(int x=1;x<=100;x++) {
switch (code){
case 1:
productArray[x-1] = Integer.parseInt(a.readLine());
productList.add(new Integer(a.readLine()) );
break;
default:
System.out.println("Invalid")
break;
}
}
You should use a List instead of an array, because you don't know a priori the length for them.
A List allows you to dinamically add an element as soon as you got it, so you should "put the array" under the user input.
List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer)
public static void main(String args[]) throws Exception) {
//...
if(code==1) //<-- This was a l, check again your code.
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
names.add(prodname); //<-- add value to ArrayList
System.out.print("Price: ");
int price = Integer.parselnt(a.readLine());
System.out.println("");
}
//...
}
To print the array content you just need to iterate over the ArrayList:
for(String prodname: names)
System.out.println(prodname); //<-- This will print all your product names
public class DataInsideArrays {
public static DataInputStream a = new DataInputStream(System.in);
List<String> productname=new ArrayList<String>();
public static void main(String args[]) throws Exception {
// rest of your code...
if(code == 1) {
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
////////////////////////to store data place arraylist here/////////////////////////////
productname.add(prod);
///////////////////// //same way use arr to store price and product no
} else if(code == 2) {
System.out.println("Display List of Products-Prices") ;
System.out.print("Enter product number:") ;
int prodnum=Integer.parseInt(a.readLine());
System.out.println("");
}
if(code == 3) {
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
}
}
Here's the correct codes for the output I want. Maybe is there any other way I can get the same output of this with different coding?
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Thank for helping me guys. Really appreciated it.

Basic Arrays in a Java Program

I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}

Categories