I'm making an ArrayList of a type 'Item' that I've created. The class has a variable called name to describe the item. The items are stored in an ArrayList.
I cannot figure out how to reference the name variable because it is producing an error in the compiler that says cannot find symbol - variable name. Specifically, I reference it like this:
for (int i=0; i < theMenu.size(); i++) {
Item temp = theMenu.get(i);
if(temp.name == keyword)
System.out.println("test");
}
I've also tried referencing it like this:
for (int i=0; i < theMenu.size(); i++) {
if(theMenu.get(i).name == keyword)
System.out.println("test");
}
It produces the same error. Please help! Here is the relevant code:
import java.util.ArrayList;
import java.util.Scanner;
public class Doms {
public static class Item {
public Item(int itemID, String itemName, double itemPrice, double itemSalePrice, String itemSaleBeginDate, String itemSaleEndDate, ArrayList<Integer> itemReviews, ArrayList<String> itemComments) {
int id = itemID;
String name = itemName;
double price = itemPrice;
double salePrice = itemSalePrice;
String SaleBeginDate = itemSaleBeginDate;
String SaleEndDate = itemSaleEndDate;
ArrayList<Integer> reviews = itemReviews;
ArrayList<String> comments = itemComments;
}
}
public static void main(String[] args) {
// A list containing each Item and all of its contents
ArrayList<Item> items = new ArrayList<Item>();
// Create Item elements
ArrayList<Integer> reviews2 = new ArrayList<Integer>();
ArrayList<String> comments2 = new ArrayList<String>();
Item item2 = new Item(2, "Sour Cream Donut", 1.29, 1.29, "", "", reviews2, comments2);
items.add(item2);
//This part doesn't work
for (int i=0; i < theMenu.size(); i++) {
Item temp = theMenu.get(i);
if(temp.name == keyword)
System.out.println("test");
}
}
}
There is a lot going on with your code that needs work, but as suggested in the comments the main issue is that the variable name for example doesn't exist in your Item class, in fact no variables exist in your Item class.
To solve this you need to create class variables that you can reference from elsewhere, note how there are defined directly in the Item class not in the Item(...) method:
public static class Item {
//Create class variables
int id;
String name;
double price;
double salePrice;
String SaleBeginDate;
String SaleEndDate;
ArrayList<Integer> reviews;
ArrayList<String> comments;
public Item(int itemID, String itemName, double itemPrice, double itemSalePrice, String itemSaleBeginDate, String itemSaleEndDate, ArrayList<Integer> itemReviews, ArrayList<String> itemComments) {
//Use the values passed into the method and store them as class variables
id = itemID;
name = itemName;
price = itemPrice;
salePrice = itemSalePrice;
SaleBeginDate = itemSaleBeginDate;
SaleEndDate = itemSaleEndDate;
reviews = itemReviews;
comments = itemComments;
}
}
Now you can create an Item and get the values like normal:
//Create an item
Item item1 = new Item(1, "Apple Fritter", 1.49, 1.29, "February 1, 2021", "July 1, 2021", reviews1, comments1);
//Get the public values from the item:
System.out.println("ID: " + item1.id);
System.out.println("Name: " + item1.name);
System.out.println("Price: " + item1.price);
And you will get the following output:
ID: 1
Name: Apple Fritter
Price: 1.49
Note as per the comments to your question you need to use the String.equals(...) method to compare strings, you can't compare strings using ==. For example this is the correct way to compare the name string to the keyword string: if(temp.name.equals(keyword))
Related
This question already has answers here:
How to convert an Array to a Set in Java
(19 answers)
Closed 2 years ago.
In my task I already put some cities in array but I now face a problem.
In main i did this:
City[] cities = enterCity(scanner);
In method enter city I had array of 3. So I needed to return name of a city and number of citizens.
In for loop I enter name and number of citizens. At the end of loop I did this:
cities[i]=new City(name, numbersOfCitizens);
and then returned it with City[] cities.
Now I need to improve my code with set.
In method I implemented:
Set<City> cities = new Hashset<>();
I failed to create method add. I tried with this to call it in main:
add.(City(name, numbersOfCitizens));
in City class and return City[] cities says inconvertible types ( so it cannot return anything). Is the right thing to call method like I do in main and if it is how to properly return all values. In class City I have usual get and set method.
Create Set
// Create new Set
Set<City> cities = new HashSet<City>();
// Add new City
cities.add(new City());
Convert Set in to array - option #1
City[] objects = cities.toArray(new City[0]);
Convert Set in to array - option #2
Manual copy:
City[] objects = new City[cities.size()];
int position = 0;
for (City city : cities) {
objects[position] = city;
position++;
}
Working example
public class SetExample {
private static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
Set<City> cities = readCities();
}
private static Set<City> readCities() {
Set<City> cities = new HashSet<City>();
int numberOfCities = 3;
for (int i = 0; i < numberOfCities; i++) {
City newCity = readCity();
cities.add(newCity);
}
return cities;
}
private static City readCity() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Numbers of citizens: ");
int numbersOfCitizens = scanner.nextInt();
return new City(name, numbersOfCitizens);
}
}
Printing
Example of the class:
class City {
private String name;
private int numbersOfCitizens;
public City(String name, int numbersOfCitizens) {
this.name = name;
this.numbersOfCitizens = numbersOfCitizens;
}
}
When you will use without adding toString() method so:
City city = new City("New York", 1234);
System.out.println(city);
you can expect output:
City#19469ea2
To print custom message, you have to override toString() method, for example generate "default" method in IntelliJ:
#Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
", numbersOfCitizens=" + numbersOfCitizens +
'}';
}
or something simple like:
#Override
public String toString() {
return name + " " + numbersOfCitizens;
}
I want to store item i1 and i2 as an array in user parameter items. I guess this part is OK.
class item {
int quty;
String name;
double nc;
public item(String name, int quty, double nc) {
this.quty = quty;
this.name = name;
this.nc = nc;
}
static item i1 = new item("I1", 10, 6.04);
static item i2 = new item("I2", 14, 8.01);
}
class user {
String name;
double nc;
item[] items; // store item objects as value of user
public user(String name, double nc, item[] items) {
this.name = name;
this.nc = nc;
this.items=items;
}
static user u1 = new user("Tenny", 10.18, new item[]{item.i1, item.i2} ); // user stores two items
}
Then I want to call items' names.
You can easly call item name by System.out.println(item.i1.name) , but I want to call names of items that user u1 has.
System.out.println("User has " + Arrays.toString((user.u1.items.name)));
Above doesn't do that. How to do that?
The way you are calling is incorrect as Items is an array type it requires index.
user.u1.items[0].name
You can use below code to print the name of all item of user.
for(item i:user.u1.items) {
System.out.println(i.name);
}
So I need to grab the itemPrice part of the index and add them all together, but i'm not sure how to go about accessing that. Can I somehow use my getCost method from the GroceryItemOrder class and continuously add it to the totalCost in the GroceryList class, or do I need to access the itemPrice and quantity part of each stored object.
public class GroceryList {
public GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
public int manyItems;
public GroceryList() {
final int INITIAL_CAPACITY = 10;
groceryList = new GroceryItemOrder[INITIAL_CAPACITY];
manyItems = 0;
}
//Constructs a new empty grocery list array
public GroceryList(int numItem) {
if (numItem < 0)
throw new IllegalArgumentException
("The amount of items you wanted to add your grocery list is negative: " + numItem);
groceryList = new GroceryItemOrder[numItem];
manyItems = 0;
}
public void add(GroceryItemOrder item) {
if (manyItems <= 10) {
groceryList[manyItems] = item;
}
manyItems++;
}
//
// #return the total sum list of all grocery items in the list
public double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ ) {
//THIS PART
}
return totalCost;
}
}
And this is GroceryItemOrder
public class GroceryItemOrder {
public String itemName;
public int itemQuantity;
public double itemPrice;
public GroceryItemOrder(String name, int quantity, double pricePerUnit) {
itemName = name;
itemQuantity = quantity;
itemPrice = pricePerUnit;
}
public double getcost() {
return (itemPrice*itemQuantity);
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public String toString() {
return (itemName + " " + itemQuantity);
}
}
Thanks for all the replies! I got it working and understand what's going on here now.
You first need to access an instance of GroceryItemOrder in the array and from there then access its itemPrice field like so,
groceryList[0].itemPrice
would give you the itemPrice of the first groceryListOrder in the groceryList array. If you want to use a method to do this instead, then add a getItemPrice method in your groceryListOrder class,
public getItemPrice() {
return itemPrice;
}
Then you can access each groceryListOrder's itemPrice in the array like so,
groceryList[0].getItemPrice()
would do the same as groceryList[0].itemPrice. If you wanna get the total cost of all the objects in the groceryList array, then use a loop to add all the itemPrice fields multiplied by the itemQuantity field (since it's the totalcost of each object being summed together) by using your getcost method,
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
totalCost += groceryList[i].getcost();
}
First of all you should encapsulate all fields ofGroceryItemOrder class, so all the fields should be private member of the class and then use their setter/getter methods to access them in GroceryList.
Secondly, this implementation has a bug. The second constructor gets numItem as input and initialize array size accordingly. But, add method does not look at the real size and that might cause invalid array index exception. Consider this code:
GroceryList list = new GroceryList(2);
for (int i=0; i<10; i++)
list.add(new GroceryItemOrder("grocery", 5, 10));
The exception will be occurred when i=2
This works for me, you would need to set static GroceryItemOrder[] groceryList = new GroceryItemOrder[0]; as well:
//
// #return the total sum list of all grocery items in the list
public static double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ )
{
totalCost += groceryList[i].getcost();
}
return totalCost;
}
i have a situation where i have to read xml files where i get three elements like this
2019-03-19,null,null
2016-11-30,null,null
2016-10-14,null,null
2016-09-30,null,null
2016-09-30,1,YEARS
2016-09-30,3,MONTHS
2016-09-30,4,MONTHS
I have to store all three items on some data structure and apply my logic like below
I have to find the max of last item and then for that i have to find the max of second item then for that i have to find the max of first element of more than one is present .
Please suggest me some idea
Create a single object like below that can hold all three data elements and is also capable of handling a "null" value for the quantity and term length values. You may want to have the constructor convert the String date (2019-03-19) into a real date object or you could handle that before object creation. Then add these objects to a data structure (i.e. list, etc) that you can use to manage and organize them.
public class ListElement {
public Date date;
public Integer qty;
public String termLength;
public ListElement(Date d, Integer q, String t) {
this.date = d;
this.qty = q;
this.termLength = t
}
// getter methods
public Date getDate() {
return this.date;
}
public Integer getQty() {
return this.qty;
}
public String getTermLength() {
return this.termLength;
}
public toString() {
return System.out.println(this.date + "::" +
this.qty + "::" +
this.termLength)
}
}
You can create an enum if you have some predefined terms:
enum Term {
AGES, YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS;
}
And use it in your class with other two types as:
public class MyObjects {
private Date date;
private Integer quantity;
private Term term;
public MyObjects(Date date, Integer quantity, Term term) {
this.date = date;
this.quantity = quantity;
this.term = term;
}
// getters, setters
}
Then define the constructor that accepts these 3 arguments and use it while processing XML file.
Two different ways to store the data. One is 2D array and the other is arraylist. All the data is type String. You would have to Parse the Integers using Integer.parseInt() to get int value. You will also have to catch for null values. This assumes that your xml data have newline characters at the end of each line.
public static void main(String[] args) {
// TODO code application logic here
//Assuming there are \n char at end of line
String xml = "2019-03-19,null,null\n" +
"2016-11-30,null,null\n" +
"2016-10-14,null,null\n" +
"2016-09-30,null,null\n" +
"2016-09-30,1,YEARS\n" +
"2016-09-30,3,MONTHS\n" +
"2016-09-30,4,MONTHS";
System.out.println("2D Array Output:");
String[][] twoDArrayExample = twoDArrayVersion(xml);
//print 2D array
for(int i = 0; i < twoDArrayExample.length; i++)
{
for(int z = 0; z < twoDArrayExample[i].length; z++)
{
System.out.print(twoDArrayExample[i][z] + " - ");
}
System.out.println();
}
System.out.println("\n\nArray List Output:");
ArrayList<ArrayList<String>> arrayListExample = arrayListVersion(xml);
//print arraylist
for(ArrayList<String> entry : arrayListExample)
{
for(String item : entry)
{
System.out.print(item + " + ");
}
System.out.println();
}
}//end of main
static String[][] twoDArrayVersion(String xml)
{
String[][] dataHolder;
String[] tempDataHolder = xml.split("\n");
dataHolder = new String[tempDataHolder.length][3];
for(int i = 0; i < tempDataHolder.length; i++)
{
String[] tempDataHolder2 = tempDataHolder[i].split(",");
dataHolder[i][0] = tempDataHolder2[0];
dataHolder[i][1] = tempDataHolder2[1];
dataHolder[i][2] = tempDataHolder2[2];
}
return dataHolder;
}
static ArrayList<ArrayList<String>> arrayListVersion(String xml)
{
ArrayList<ArrayList<String>> dataHolder = new ArrayList();
String[] tempDataHolder = xml.split("\n");
for(int i = 0; i < tempDataHolder.length; i++)
{
ArrayList<String> tempArrayList = new ArrayList();
String[] tempDataHolder2 = tempDataHolder[i].split(",");
tempArrayList.add(tempDataHolder2[0]);
tempArrayList.add(tempDataHolder2[1]);
tempArrayList.add(tempDataHolder2[2]);
dataHolder.add(tempArrayList);
}
return dataHolder;
}
I just started working with arrayLists - basically what I need to figure out is how to search my arrayList and if that same object is found to add a new total value to it versus just swapping it out.
ie.
arrayList = (hats, $45)
and I have a new value to add to hats (ie. $10 dollars) - so the ultimate new total for hats = $55
...and if hats are not in the list already to add it.
Any help is appreciated !
Filling an ArrayList with String and Integer will not be possible unless you use a nested ArraysList or Map.
But you can create a simple class for your ProductName and the Price and create An ArraysList which contains for the Name and price.
public class Products {
private String product;
private int price;
public Products(String product, int price){
this.product = product;
this.price = price;
}
public String getProduct(){
return this.product;
}
public int getPrice(){
return this.price;
}
#Override
public String toString(){
return this.product +" "+ this.price;
}
public static void main(String[] args) throws ParseException {
ArrayList<Products> list = new ArrayList<>();
list.add(new Products("Hat",45));
list.add(new Products("Socks",10));
for (Products gd: list){
if (gd.getProduct().equals("Hat")){
int index = list.indexOf(gd);
list.set(index,new Products(gd.getProduct(),gd.getPrice+10));
}else {
// if productName not found
System.out.println("sorry products not available");
break;
}
}
System.out.println(list);
}
}
output:
[Hat 55, Socks 10]
But if you don't want all this class and want to still use the ArrayList for the job then you can do this with ArrayList containing both name and price
ArrayList<String> list = new ArrayList<>();
list.add("Hat,45");
list.add("Socks,15");
for (String ss:list){
String[] spl = ss.split(",");
if (spl[0].equals("Hat")){
int index = list.indexOf(ss);
int value = Integer.parseInt(spl[1]) +10;
list.set(index,(spl[0]+","+value));
}
}
System.out.println(list);
output:
[Hat,55, Socks,15]