How to allow user to make edits to an array - java

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()))

Related

cant find a way for my code to scan how many integers were inputted to set array length and to have it set those integers in an array

import java.util.*;
public class Commission {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter sales amount separated by space:");
double[] saleAmounts = Inputs(input);
}
Below is where my function scans numbers, but I need it to scan an x amount of values entered 'at the same time' to set the array length. Also, I need it so the user only enters in values once
(i have the length at 5 for a logic test)
private static double[] Inputs(Scanner sc) {
double[] sales = new double[5];
for (int i = 0; i < sales.length; i++){
sales[i] = sc.nextDouble();
}
return sales;
}
Array is a data structure with set size. If you want to have dynamic sized 'array', use List or ArrayList for example.
From the user, read an entire line (they enter values separated by spaces and hit enter), then pass that to your method and split it on space.
Something like: no exception checking included
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter sales amounts separated by spaces, then hit Enter: ");
double[] saleAmounts= Inputs(input.nextLine());
for(int i=0; i < saleAmounts.length; i++)
{
System.out.println("index " + i + " : " + saleAmounts[i]);
}
}
private static double[] Inputs(String inputLine)
{
String[] values = inputLine.split(" ");
double[] sales = new double[values.length];
for (int i = 0; i < values.length; i++)
{
sales[i] = Double.parseDouble(values[i]);
}
return sales;
}

Shopping Cart - Array not storing a value

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]);
}
}
}

Java array and nextInt(); do not work properly

Hello guys I am having a problem with an array and a .nextInt(); this is causing my output line at the 3rd prompt to shift up instead of under, and seriously cannot figure out what's wrong.
I have tried .hasNextInt(); but nothing, it actually gives me an error, so here is the code:
import java.util.Random;
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn); //my problem
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //my problem
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2];
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
// Method for calculations
public static double compute(int numOfSimulation, int numOfPeople)
{
for (int i =0; i < numOfPeople; i++)
{
Random rnd = new Random(1);
//Generates a random number between 0 and 364 exclusive
int num = rnd.nextInt(364);
System.out.println(num);
System.out.println(num / 365 * numOfPeople * numOfSimulation);
}
return numOfPeople;
}
}
Found it!!!!!!!!!!!
do this:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return(userInput);
}
To return the array
Let me know!
I actually don't think you can do it there with that userInput, I am saying this because the methodology of doing this program is quite arcane.
You are then calling 2 arrays at prompting, I wonder if you might change that to one what will change such as:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
As also the return promptAndRead(stdIn); might be part of the problem
Don't know though just trowing suggestions at Markov ;)

How do I output a TABLE with names and scores with only using Arrays and Methods?

I have been trying to find the answer to this question but to no avail!
Basically I have to write a program where 'x' number of players can enter a guessing game and input their guesses and then get a score.
However, right after they input their guesses, i have to output it in a table form like this "NAME GUESS SCORE"
I do not know how i can do this with a for loop since a for loop println can only print values from playersArray. How can I print another array like guessesArray to the side of it?
I can only use Arrays and Methods to do this.
Below I will show u what i have right now:
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class game
{
static int[] guessesArray;
static int guess;
static String [] playersArray;
static int[] currscoresArray;
static int [] addscoresArray;
static int [] finalscoresArray;
public static void main(String [] args){
System.out.print("Number of players? ");
Scanner kb = new Scanner(System.in);
int numplayers = kb.nextInt();
//Initialize
playersArray = new String[numplayers];
guessesArray = new int [numplayers];
currscoresArray = new int [numplayers];
addscoresArray = new int [numplayers];
finalscoresArray = new int [numplayers];
populateArray(playersArray);
displayMenu();
}
public static void populateArray( String[] x){
Scanner kb = new Scanner(System.in);
for (int i = 0; i<x.length ; i++){
System.out.print("Enter Player "+(i+1)+": ");
x[i]=kb.nextLine();
}
}
public static void displayMenu(){
int choice=0;
Scanner kb = new Scanner(System.in);
String[] args = {};
while(true){
System.out.println("Menu ");
System.out.println("1. Make Guess");
System.out.println("2. List Winner");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = kb.nextInt();
if (choice==0){
System.out.print("Do you want to play a new game? Y/N: ");
String ans = kb.next();
if (ans.equals ("Y") || ans.equals ("y")){
main(args);
}
break;
}
switch (choice){
case 1: makeGuess(); break;
case 2: listWinner(); break;
default: System.out.println("Invalid choice");
}
}
System.out.println("End of program");System.exit(0);
}
public static void makeGuess(){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int secret = rand.nextInt(10)+1;
for (int i=0; i < guessesArray.length; i++){
System.out.print("Enter your guess "+playersArray[i]+": ");
guessesArray[i]=kb.nextInt();
}
int diff = (int)(Math.abs(guess - secret));
int score=0;
if (diff == 0){
score=score+10;
}else if(diff<=1){
score=score+5;
}else if(diff<=2){
score=score+2;
}
for (int i=0; i< currscoresArray.length; i++){
currscoresArray[i]=score;
}
System.out.println();
System.out.println("Generated number is "+secret);
System.out.println("Current Score Listing");
System.out.println(" Name Guess Score Added Final Score");
System.out.println("1. "+playersArray[0]+" \t "+guessesArray[0]+" \t"+currscoresArray[0]+"");
System.out.println("1. "+playersArray[1]+" \t "+guessesArray[1]+" \t"+currscoresArray[1]+"");
}
public static void listWinner(){
}
}
just reuse a int x variable when printing from each array?
for( int x = 0; x < playersArray.length; x++ ) {
System.out.println( playersArray[ x ] + ” ” + guessArray[ x ] + " " + finalScoresArray[ x ] );
}
you already give an example in your code where you print the 3 values with a single print method. you used a for loop for indexing an element in an array. So combing the 2 techniques shouldn't be too difficult to grasp.
Instead of using an enhanced for loop (e.g. for (String player : playersArray) {}, you can use an indexed one:
for (int i = 0; i < playersArray.length; i++) {
String name = playerArray[i];
double score = scoresArray[i];
}
That being said, you should really make a Player class, that holds all information of a single player, and then have just one array, of that type. That's much nicer, not only because you can use enhanced fors, but because you don't need to make sure the arrays are always synced, and your code becomes way easier to understand.

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.

Categories