4

How I would get the 3 items from user input Item (name, cost, priority) into one object item and place that object item into an array of other objects?

public class Main {

    public static void main(String[] args) {
       //here are my variables.  
       //I'm pretty sure a few of these should be defined 
       //  in their own item class. 
       int i=0;
       String name1;
       int priority1; 
       double cost1;

       //String[] shoppingList = new String[7];
       String[] item  = new String[7];

       // I am able to grab input from the user for all 3 elements of 
       //   an item object (name, cost, priority)
       // I am missing how to save these 3 elements into an item object 
       //  and create an array for each item object
       for (i=0; i<item.length;i++)  {

          //I want to capture name, priority, and cost of each item
          //  and add each item as an in
           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();
FlipMcF
  • 12,636
  • 2
  • 35
  • 44
user2558595
  • 399
  • 3
  • 6
  • 12

5 Answers5

8

"How I would get the 3 items from user input Item (name, cost, priority) into one object item"

If I understand you correctly, the solution would be to make a new class. Call it whatever is relevant for what you're doing

class Data {
    String name;
    double cost;
    int priority;
    Data(String name, double cost, int priority) { //Set variables }
}

Then you can create a new "Data" class with your relevant information with:

Data myObject = new Data("Input1", 37.50, 2);

Just for example, with random information. You can make as many of these unique objects as you'd like, and add them to an array or ArrayList depending on what you want to do:

Data[] myArray = new Data[100];
//or
List<Data> myList = new ArrayList<Data>();
Kon
  • 10,702
  • 6
  • 41
  • 58
  • You mean "then you can create a new 'Data' object" right? – DimiDak Mar 10 '19 at 20:23
  • @DimiDak That's right, you create objects from the class (which can be thought of as a definition/template for object creation). – Kon Mar 10 '19 at 22:24
  • Thanx, you seem to know a lot about java. Would this be possible to complete your answer including user input etc? I am trying to combine the answers below and adjust them to my problem. – DimiDak Mar 10 '19 at 22:45
3

You could try a custom class:

public class Item {
    private String name;
    private double price; // you should probably use an 'int' for this
                          // it would be the amount of cents
                          // that would avoid rounding errors
    private int priority;
    public Item(String name, double price, int priority) {
        this.name = name;
        this.price = price;
        this.priority = priority;
    }
    // (getters and setters)
    public String getName() {
        return name;
    }
    ...
}

Item milk = new Item("milk", 19.99, 3); // wow, expensive milk :P
Item[] items = [milk, new Item("cheese", 99.99, 2), ...];
tckmn
  • 57,719
  • 27
  • 114
  • 156
2

What you could do is create a class, and use the constructor to help pass parameters. You could then make an instance of this class, and use it to set the parameters to whatever you need (i.e the name, price, etc.). Then accept the user input using the Scanner, and what I would do, is make an ArrayList of (I'll call it ItemData). Then, add the instance to the ArrayList using .add(this). Here's the code for each step:

  1. Pass the parameters in the constructor:

    public class ItemData{
        public ItemData(String name, double cost, int priority){
        }
    }
    
  2. Make a new instance of ItemData in the Main class at the end of the input:

    ItemData itemData = new ItemData(name, cost, priority);
    
  3. Make the ArrayList field (make sure you import java.util.ArrayList and java.util.List) :

    List<ItemData> dataStorage = new ArrayList<ItemData>();
    
  4. Add the instance of ItemData to the ArrayList into the ItemData constructor:

    Main.(ArrayList name here).add(this);
    

Your final code should look like this:

public class ItemData{
    public ItemData(String name, double cost, int priority){
        Main.itemData.add(this);
    }
}


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 x = new ItemData(name, cost, priority);
        }
    }
}
  • That constructor looks so simple and shortcut like. I don't typically write java. Is that a short-cut way of defining and setting this.name, this.cost, and this.priority? – FlipMcF Jul 19 '13 at 21:54
  • In intellij: right click --> generate -->Constructor (Or cmd+N in mac) – DimiDak Mar 10 '19 at 20:16
1

Your item class:

class Item {
    String name;
    double cost;
    int priority;
    Item(String name, double cost, int priority) { 
        this.name = name;
        this.cost = cost;
        this.priority = priority;
    }
}

"An Array of objects" is a misnomer in Java, because arrays have fixed-length elements. I do not think it's safe to assume all your Item objects will be the same size.

Use a "List" - or in Java, an "ArrayList"

ArrayList<Item> myCart = new ArrayList<Item>();

Create the item object:

Item myItem = new Item('cheese', 42.12, 1);  //cheese is good

Append the item to the shopping cart:

myCart.add(myItem);

http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html Creating an Arraylist of Objects

Community
  • 1
  • 1
FlipMcF
  • 12,636
  • 2
  • 35
  • 44
1

You should try making a User Defined Type which acts as a data structure to hold the values you desire.

Since java is an object oriented language, you can create a user defined type with a class. Below, I created a class called Item with three member data variables. This class is a blueprint for all Item type objects. Whenever you create a new item object, it will have its own unique copies of the member data variables.

For sake of simplicity, I did not encapsulate the member data variables, but for future programs you should declare member data variables private and provide an interface to access/modify them. Leaving them public here allows me the convenience of accessing them with the dot (.) operator.

See the following code for a working example

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Item {

public String name;
public int priority;
public double cost;

public static void main(String[] args) {


int itemAmount = 7;
List<Item> itemList = new ArrayList<Item>();


    for (int i=0; i < itemAmount; i++)  {
        Item itemToCreate = new Item(); 
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter item name " + i);
        itemToCreate.name = keyboard.next();


        Scanner keyboard2 = new Scanner(System.in);
        System.out.println("Enter the price of item " + i);
        itemToCreate.cost = keyboard2.nextDouble();

        Scanner keyboard3 = new Scanner(System.in);
        System.out.println("Enter Priority Number " + i);
        itemToCreate.priority = keyboard3.nextInt();

        itemList.add(itemToCreate);
    } // end for

    for (int i=0; i < itemList.size(); i++) {
        Item tempItem = itemList.get(i);
        System.out.println("Item " + tempItem.name + " has cost " + tempItem.cost + " with priority " + tempItem.priority);
    }



} // end main

} // end class

You should notice I replaced your original declaration with an ArrayList data structure. This is a dynamic data structure that can grow as you insert items into it. You should take on the challenge of allowing for unlimited amount of user input and to account for an unknown quantity of Item objects in your list.

Hope this helps!

Paul Renton
  • 2,652
  • 6
  • 25
  • 38