Creating Array or ArrayList from class ojects - java

I have been working on this for a while, but can't quite seem to figure out how to add an item to an ArrayList. I would like to add grocItem (should be 7 grocItems from user input from for loop) into an ArrayList of grocList:
public class ItemData{
public ItemData(String name, double cost, int priority){
Main.(ArrayList grocList).add(grocItem);
// Main.groclist.add(grocItem);
}
}
Main Class:
import java.util.*;
public class Main {
public static List<ItemData> itemData = new ArrayList<ItemData>();
public static void main(String[] args) {
int i=0;
//String name1;
//int priority1;
//double cost1;
String[] item = new String[7];
for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
ItemData grocItem = new ItemData(name, cost, priority);
}
//How do I add grocItem to an Array list of other grocItems (6 grocItems from user input array item)
Main.itemData.add(groclist);
}
}

Change your code, add the method inside the loop.
for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
ItemData grocItem = new ItemData(name, cost, priority);
itemData.add(grocItem ); // add here
}

You should add the ItemData object to your arraylist inside your loop:
for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
ItemData grocItem = new ItemData(name, cost, priority);
itemData.add(groclist); // <-- add to arraylist inside the loop
}

Related

How do I access the String value inside a for loop?

Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}

Why can I not input a number of itemNumber at line 38

My code breaks when the user is supposed to input a unique number for itemNumber, however there is no error displayed in NetBeans, can someone help me with why this happens?
package pre_release;
import java.util.*;
public class Pre_Release {
public static void main(String[] args) {
int numberOfItems = 0;
int number;
int bidNumber;
double highestBid = 0;
Scanner userInput = new Scanner (System.in);
Scanner userString = new Scanner (System.in);
Scanner userDouble = new Scanner (System.in);
Scanner userBuyer = new Scanner (System.in);
Scanner userInt = new Scanner (System.in);
Scanner userItem = new Scanner (System.in);
do{
System.out.println("Please enter the the amount of items for the auction. Needs to be more than or equal to 10");
numberOfItems = userInput.nextInt();
} while(numberOfItems<10);
String[] description = new String[numberOfItems];
double[] reservePrice = new double[numberOfItems];
double[] bid = new double[numberOfItems];
int[] itemNumber;
itemNumber = null;
int[] buyNumber = new int[numberOfItems];
for(int count=0;count<numberOfItems;count++){
System.out.println("Input a number for each item number");
itemNumber[count] = userInt.nextInt();
}
for(int count=0;count<numberOfItems;count++){
bidNumber=0;
System.out.println("Please give your item a reserved price");
reservePrice[count] = userDouble.nextDouble();
System.out.println("Please describe your item");
description[count] = userString.nextLine();
}
System.out.println("Please enter the desired item you wish to see");
number = userInt.nextInt();
for(int count2=0;count2<numberOfItems;count2++){
if(itemNumber[count2] == number){
System.out.println("The reserved price is" + reservePrice[numberOfItems]);
System.out.println(description[numberOfItems]);
}
System.out.println("Would you like to put a bid on this item? Needs to be more than" + reservePrice[numberOfItems]);
}
}
}
Haven't seen your error message, but probably you've got the error because your array reference is null
int[] itemNumber;
itemNumber = null
In order to fix this, replace these lines with this one:
int[] itemNumber = new int[numberOfItems];

How do i use user input for a string array that is in a while loop?

I'm trying to convert the user input from the question of students name and score into a array.
I also need help to printout the array.
The while loop is using boolean loopNaming as its condition, and i is updated everytime the loop occurs.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
String[] name = new String[i];
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1;
}
System.out.println(name[i]);
}
}
You can simplify the logic of your program and write something like this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> nameList = new ArrayList<String>();
List<Double> scoreList = new ArrayList<Double>();
while (true) {
System.out.printf("Enter first name of student or done to finish: ");
String fname = keyboard.next();
if (fname.equals("done")) {
break;
}
System.out.printf("Enter last name of student: ");
String lname = keyboard.next();
nameList.add(fname + " " + lname);
System.out.println("Enter score: ");
scoreList.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println("Names: " + nameList);
System.out.println("scores: " + scoreList);
}
I have changed the array to an arraylist and moved i=i+1; to inside else segment. Also changed the final print statement to print the list.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<String>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name.add(keyboard.next());
if(name.get(i).equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i=i+1;
}
}
System.out.println(name);
}
I would firstly recommend using a List data structure:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming = true;
List<String> name = new ArrayList<>();
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
}
System.out.println(name.toString());
}
However, if you very much would like to use an array, you could make your own method to increase the size of your array each time a new name is added:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
int i = 0;
boolean loopNaming = true;
String[] name = {};
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name = increaseArray(name);
name[i] = input;
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i++;
}
}
System.out.println(Arrays.toString(name));
}
public static String[] increaseArray(String[] arr) {
String[] temp = new String[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
return temp;
}
I was unsure what your plan was with your score variable, but this would be two ways to achieve your desired result.
I hope this helps.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if(input.equals("done"))
{
loopNaming = false;
}
else
{ name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1; //no need to use
}
System.out.println(name);
}
You should use a dynamic list because You can't resize an array in Java. The second point when the user gives "done", you should not put it in the list so check it before the insertion.
You declared your String array with size 0. that's why you cant add elements in to it.
import java.util.Scanner;
public class NameArray {
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
double score[] = new double[10];
boolean loopNaming=true;
int i=0;
String namae;
String[] name = new String[10];
int count = 0;
while(loopNaming==true){
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done")){
loopNaming = false;
}
else{
System.out.println("Enter score: ");
score[i] = keyboard.nextDouble();
count++;
}
i=i+1;
}
for(int j = 0; j < count; j++) {
System.out.println(name[j]+" "+score[j]);
}
}
}
Try this code or you can go for any other data structures.

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

How Can i Use The Values Of The Int in The Scanner

int CMC = 279;
int BDM = 326;
int CP = 177;
int CB = 228;
int CR = 190;
int PC = 43;
int CCS = 24;
int CE = 26;
int FM = 20;
int originalpricebake ;
Scanner bakeorder1 = new Scanner(System.in);
int order1;
System.out.print("\nEnter Your 1st Item Order:");
order1 = bakeorder1.nextInt();
Scanner bakeorder2 = new Scanner(System.in);
int order2;
System.out.print("\nEnter Your 2nd Item Order:");
order2 = bakeorder2.nextInt();
Scanner bakeorder3 = new Scanner(System.in);
int order3;
System.out.print("\nEnter Your 3rd Item Order:");
order3 = bakeorder3.nextInt();
Scanner bakeorder4 = new Scanner(System.in);
int order4;
System.out.print("\nEnter Your 4th Item Order:");
order4 = bakeorder4.nextInt();
Scanner bakeorder5 = new Scanner(System.in);
int order5;
System.out.print("\nEnter Your 5th Item Order:");
order5 = bakeorder5.nextInt();
originalpricebake = order1 + order2 + order3 + order4 + order5;
System.out.print("\nThe Current Price: " + originalpricebake);
how can i use the integer values on the top when i scan for an user input for his order? So that when i got the user input an equation will be made at the bottom of the code
Use Array to store the values and access it using loop.
int order;
int price=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many orders: ");
order = Integer.parseInt(scan.nextLine());
//Create an integer array to store the input
int bakeorder[] = new int[order];
//int originalbakeprice[] = new int[order];
for(int i=0;i<order;i++)
{
System.out.print("Enter the order " + (i+1) + " : ");
bakeorder[i] = Integer.parseInt(scan.nextLine());
price +=bakeorder[i];
}
System.out.println(price);

Categories