Ignore existing item in the LInkedList - java

I am trying to ignore the existing item that I added in the duplicate.
Normally, if the item does not exist it will eventually added the item to the
LinkedList
When I try to added item again, I just wanted to ignore the adding process and the increment the value by 1.
But the problem is it keep adding the items to the LinkedList.
Can someone explain to me?
class Item{
Store store;
String name;
String code;
String number;
public Item(String name, String code){
this.name = name;
this.code = code;
number = 0;
}
public boolean itemExists(String name, String code){
return this.name.equals(name) && this.code.equals(code);
}
public void increment(){ number++; }
#Override
public String toString(){ return store.getName()+ " " + name + " " + code + " " +number; }
}
Items will be added to the factory.
class Factory{
private LinkedList<Item> items = new LinkedList<Item>():
private String name;
private String number;
public Factory(String name, String number){
this.name = name;
this.number = number;
}
public void getName(){
return name;
}
public void addItem(String name, String code){
items.add(new Item(this, name, code));
}
#Override
public String toString(){ return name + " " + number; }
public List<Item> getItems{
return items;
}
}
The factory then delivery to the store.
class Store{
private LinkedList<Factory> factories = new LinkedList<>();
public Store(){
factories.add(new Factory("MayFlower", "01");
factories.add(new Factory("SunFlower", "02");
factories.get(0).addItem("GTA", "001A");
factories.get(0).addItem("GTA", "002A");
factories.get(0).addItem("GTA", "003A");
factories.get(1).addItem("Sonic", "022A");
factories.get(1).addItem("Sonic", "023B");
factories.get(1).addItem("Sonic", "024C");
}
public List<Item> getItemFromFact(){
List<Item> temp = new ArrayList<>();
for(Factory factory: factories)
for(Item item: factory.getItems())
temp.add(item);
return temp;
}
}
The customer buy items at the store.
class Customer{
private LinkedList<Item> items = new LinkedList<>();
public static void main(String args[]){
new Customer.view();
}
private void view(){
for(Item item: items)
System.out.println(item);
}
private void adding(){
String name = "GTA";
String code = "001A":
List<Item> item = item(name, code);
if(!item.isEmpty()){
items.add(item);
item.increment(); // will increment the value;
}
else{
System.out.println("Item does not exists");
}
}
private List<Item> item(String name, String code){
List<item> temp = new ArrayList<>();
List<item> fromStore = new Store().getItemFromFact();
for(Item item: fromStore)
if(item.itemExists(name, code))
temp.add(item)
return temp;
}
}
The main problem is in the item class under item(). If I try with the same item again, it will just add another it become like this.
MayFlower GTA 001A 1
MayFlower GTA 001A 1
The result should be
MayFlower GTA 001A 2
after I added another item.
I problem I have is that I don't know how to match the item from exisiting.
If someone know the solution.
That's would be very helpful thanks.

There are so many problems in your design and code. I've discussed some of them as given below:
I do not understand why you need a reference to Store in Item. An Item should not know which Store or Factory it is going to belong to.
I also didn't understand the purpose of the attribute, number in Store. An Item shouldn't know how many numbers of it is present in a Store or Factory. If you keep it for any reason, it should be of a numeric type (e.g. int, double etc.) so that you can perform arithmetic operations on it.
Instead of a LinkedList of Item objects in Factory, you should have a variable of type, Map<String, Integer> and you can call it stock. The key in this Map is the unique identifier of the item, which is the combination code and name as per your requirement and the value will be the available number/quantity of the Item. Given below is a minimal verifiable example of how you can maintain stock:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class Item {
String name;
String code;
public Item(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
#Override
public String toString() {
return "Name: " + name + "Code :" + code;
}
}
class Factory {
private Map<String, Integer> stock = new HashMap<String, Integer>();
private String name;
public Factory(String name) {
this.name = name;
}
public void addItem(Item item) {
if (item != null) {
String key = item.getName() + ":" + item.getCode();
stock.put(key, stock.getOrDefault(key, 0) + 1);
}
}
public void showStock() {
for (Entry<String, Integer> entry : stock.entrySet()) {
System.out.println("Item = " + entry.getKey() + ", Available quantity = " + entry.getValue());
}
}
}
public class Main {
public static void main(String[] args) {
Factory factory = new Factory("MayFlower");
factory.addItem(new Item("GTA", "001A"));
factory.addItem(new Item("GTA", "001A"));
factory.addItem(new Item("GTA", "002A"));
factory.addItem(new Item("GTA", "003A"));
factory.addItem(new Item("GTA", "003A"));
factory.addItem(new Item("GTA", "003A"));
factory.showStock();
}
}
Output:
Item = GTA:002A, Available quantity = 1
Item = GTA:003A, Available quantity = 3
Item = GTA:001A, Available quantity = 2

Related

Javafx observable list of values that are themselves observable?

right now I have the following:
ObservableList<Person> personsList;
and my UI for displaying the person list is tied to personsList.
Person is something like below:
class Person {
Name name
// other details
List<SomeItem> list;
}
// Item is immutable, but SomeItem can mutate by setting and getting the Items
class SomeItem {
Item item
Item item2
}
The issue is SomeItem is mutable, so I would want any changes to SomeItem be propagated to the original personsList.
How would I achieve something like that?? Based on googling I kind of have the following modifications, but I am not sure if they work!
class Person {
Name name
// other details
List<SomeItem> list; // <-- change to ObservableListValue<SomeItem>
}
// Item is immutable, but SomeItem can mutate by setting and getting the Items
class SomeItem {
Item item // <-- change to ObservablePropertyBase<Item>
Item item2 // <-- change to ObservablePropertyBase<Item>
}
From what I understand, this changes would make SomeItem report when any ObservablePropertyBase<Item> changes, and then ObservableListValue<SomeItem> would propagate this changes up, which would be caught by personsList?
Edit: Question 2:
Is it possible to force refresh personsList? Lets say I make an overall update to a specific SomeItem, then I can refresh the entire personsList?
You can fire Change events by creating an ObservableList with an extractor.
Here is an example:
Name.java:
public class Name {
private final String name;
public Name(String name) {
this.name = name;
}
public final String getName() {
return name;
}
}
Item.java:
public class Item {
private final String name;
public Item(String name) {
this.name = name;
}
public final String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
SomeItem.java:
public class SomeItem {
private final ObjectProperty<Item> item1 = new SimpleObjectProperty<>(this, "item1");
private final ObjectProperty<Item> item2 = new SimpleObjectProperty<>(this, "item2");
public SomeItem(Item item1, Item item2) {
this.item1.set(item1);
this.item2.set(item2);
}
public final ObjectProperty<Item> item1Property() {
return item1;
}
public final Item getItem1() {
return item1.get();
}
public final void setItem1(Item item) {
item1.set(item);
}
public final ObjectProperty<Item> item2Property() {
return item2;
}
public final Item getItem2() {
return item2.get();
}
public final void setItem2(Item item) {
item2.set(item);
}
#Override
public String toString() {
return "[" + item1.get() + ", " + item2.get() + "]";
}
}
Person.java:
public class Person {
private final Name name;
private final ObservableList<SomeItem> someItems = FXCollections.observableArrayList(someItem ->
new Observable[]{someItem.item1Property(), someItem.item2Property()});
public Person(Name name, SomeItem... someItems) {
this.name = name;
this.someItems.addAll(someItems);
}
public final Name getName() {
return name;
}
public final ObservableList<SomeItem> getSomeItems() {
return someItems;
}
#Override
public String toString() {
return "[name=" + name.getName() + ", someItems=" + someItems + "]";
}
}
App.java:
public class App extends Application {
#Override
public void start(Stage stage) {
SomeItem someItem1 = new SomeItem(new Item("item1"), new Item("item2"));
SomeItem someItem2 = new SomeItem(new Item("item3"), new Item("item4"));
SomeItem someItem3 = new SomeItem(new Item("item5"), new Item("item6"));
SomeItem someItem4 = new SomeItem(new Item("item7"), new Item("item8"));
Person person1 = new Person(new Name("person1"), someItem1, someItem2);
Person person2 = new Person(new Name("person2"), someItem3, someItem4);
ObservableList<Person> persons = FXCollections.observableArrayList(person ->
new Observable[]{person.someItemsProperty()});
persons.addAll(person1, person2);
persons.addListener((ListChangeListener<Person>) c -> {
while (c.next()) {
if (c.wasUpdated()) {
System.out.println("Updated persons:");
IntStream.range(c.getFrom(), c.getTo())
.mapToObj(index -> "Person at index " + index + " was updated to: " + c.getList().get(index))
.forEach(System.out::println);
}
}
});
// Update items to trigger change event for testing
someItem1.setItem1(new Item("item1Updated"));
someItem4.setItem2(new Item("item8Updated"));
}
public static void main(String[] args) {
launch();
}
}
Output:
Updated persons:
Person at index 0 was updated to: [name=person1, someItems=[[item1Updated, item2], [item3, item4]]]
Updated persons:
Person at index 1 was updated to: [name=person2, someItems=[[item5, item6], [item7, item8Updated]]]

Need various ways to come up with this output

I am supposed to come up with this output.
But I am getting this instead..
Here is my code:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Sample{
private String name;
private Hashtable customers = new Hashtable();
private Hashtable movies = new Hashtable();
public Sample(String aName){
name = aName;
}
public String getName(){
return name;
}
public void setName(String aName){
name = aName;
}
public void addCustomer (Customer customer) {
customers.put(customer.getName(), customer);
}
public Customer getCustomer (String customerName) {
return (Customer)customers.get(customerName);
}
public void addMovie (Movie movie) {
movies.put(movie.getName(), movie);
}
public Movie getMovie (String movieName) {
return (Movie)movies.get(movieName);
}
public void error (String message) {
System.out.println ("ERROR: " + message);
}
public Enumeration getMovies() {
return movies.elements();
}
public Enumeration getCustomers() {
return customers.elements();
}
public void showAll() {
System.out.println ("name: "+ this.getName());
Enumeration kk = this.getCustomers();
while (kk.hasMoreElements()) {
Customer one = (Customer) kk.nextElement();
System.out.println (one.show());
}
Enumeration ff = this.getMovies();
while (ff.hasMoreElements()) {
Movie one = (Movie) ff.nextElement();
System.out.println (one.show());
}
}
public void test() {
Customer k1 = new Customer ("Jonah") ; this.addCustomer (k1);
Customer k2 = new Customer ("Hellen") ; this.addCustomer (k2);
Customer k3 = new Customer ("Agnes") ; this.addCustomer (k3) ;
Movie f1 = new Movie ("StarWars"); this.addMovie (f1) ;
Movie f2 = new Movie ("Shrek"); this.addMovie (f2) ;
System.out.println("-**-**- test part 1 -**-**-") ;
this.showAll();
System.out.println("-**-**- test part 2 -**-**-") ;
System.out.println("---" + k1.getName() + " rents " + f1.getName());
this.showAll();
k1.doRent(f1);
MY CUSTOMER CLASS:
package eric;
public class Customer {
String name;
public Customer(String nameCus){
name = nameCus;
}
public String getName(){
return name;
}
public String show(){
return name;
}
public void doRent(Movie f1) {
System.out.println(" -"+ " RentData" + "[" + getName() +"," + f1.getName() + "]" );
}
}
MY MOVIE CLASS:
public class Movie {
String name;
int x = 0;
public Movie(String nameMov){
name = nameMov;
}
public String getName(){
return name;
}
public String show(){
return name+"\n"+" - average: "+x +" days\n"+" - number of rentings: "+x ;
}
}
My problem is that i cannot find a way to fix -RentData [Jonah,StarWars] under the name Jonah... Instead it comes at the end of output.. I need some one to help me figure how am ganna do that.. thanks
You're calling k1.doRent(f1) before this.showAll() so naturally you will get the "RentData..." line printed before the names are printed. The way your code is now is not conducive to what you're trying to do at all. Your Customer class should have a member list called rentedMovies that is populated every time you call doRent(...) on a Customer object. Then, Customer.show() should print the name of the customer, followed by your "RentData..." stuff that comes from rentedMovies.

Why can't I get my combobox to show me my ArrayList?

I have an arraylist called CountryList, which is a list of countries, and then I have used the code
jComboBox1.addItem(countries);
to try and add the arraylist into the combobox, but nothing happens, there's no list of countries showing up.
I can't seem to find anywhere that shows why this wouldn't work.
Here is the code that I was told should hold all countries within it:
public class CountryList
{
public static void main(String[] args)
{
List<Country> countries = new ArrayList<Country>();
Locale[] locales = Locale.getAvailableLocales();
for (Locale locale : locales)
{
String iso = locale.getISO3Country();
String code = locale.getCountry();
String name = locale.getDisplayCountry();
if (!"".equals(iso) && !"".equals(code) && !"".equals(name))
{
countries.add(new Country(iso, code, name));
}
}
Collections.sort(countries, new CountryComparator());
for (Country country : countries)
{
System.out.println(country);
}
}
}
class CountryComparator implements Comparator<Country>
{
private Comparator comparator;
CountryComparator()
{
comparator = Collator.getInstance();
}
public int compare(Country o1, Country o2)
{
return comparator.compare(o1.name, o2.name);
}
}
class Country
{
private String iso;
private String code;
public String name;
Country(String iso, String code, String name)
{
this.iso = iso;
this.code = code;
this.name = name;
}
public String toString()
{
return iso + " - " + code + " - " + name.toUpperCase();
}
}
EDIT
for (CountryList country : countries)
{
jComboBox1.addItem(country);
}
Use a default combo box model.
jComboBox1.setModel(new DefaultComboBoxModel(countries.toArray()));
You need to add one country at a time, not the whole ArrayList. You can loop through each item and add it to the combobox.
for(int i = 0; i < countries.size(); i++) {
jComboBox1.addItem(countries.get(i));
}

Which utility class can be used to store and apply sort in Java

I'm a bit confused that which of the utility classes can be used for this type of problem:
I have a file Movies.txt containing info like: Id, Name, Director, Rating. Rating may or may not be present.
Sample:
1,ABC,Mr. xyz,4.5
3,GHI,Mr. mno
2,DEF,Ms. stu,3
I need to read and store this file to the memory and then apply sort by rating as well as by name and then write to the file later on.
Which utility class can best help me in this situation, so that it can be an ease to do this if possible. No more files to be used.
Start by defining a Object that describes the basic properties of a "Movie". Take make your life easier, it might be a good idea to implement Comparable<Movie> directly.
public class Movie implements Comparable<Movie> {
private int id;
private String name;
private String directory;
private double rating;
public Movie(int id, String name, String directory, double rating) {
this.id = id;
this.name = name;
this.directory = directory;
this.rating = rating;
}
public int getId() {
return id;
}
public String getDirectory() {
return directory;
}
public String getName() {
return name;
}
public double getRating() {
return rating;
}
#Override
public int compareTo(Movie o) {
int diff = (int) asInt(getRating()) - asInt(o.getRating());
if (diff == 0) {
diff = getName().compareTo(name);
}
return diff;
}
protected int asInt(double value) {
String text = Double.toString(value);
text = text.replaceAll("\\.", "");
return Integer.parseInt(text);
}
#Override
public String toString() {
return getId() + ", " + getName() + ", " + getDirectory() + ", " + getRating();
}
}
Create a List to hold the incoming movies
List<Movie> movies = new ArrayList<Movie>(25);
Read the contents of the and parse each line into their separate property elements (I'll leave that you), add each newly create Movie to the list...
movies.add(new Movie(...));
Use Collections.sort(movies) to sort them...
For example...
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<Movie> movies = new ArrayList<Movie>(5);
movies.add(new Movie(1, "ABC", "Mr. xyz", 4.5));
movies.add(new Movie(2, "GHI", "Mr. mno", 0));
movies.add(new Movie(3, "DEF", "Ms. stu", 3));
movies.add(new Movie(4, "AT1", "Mr. T", 3));
System.out.println("Before....");
for (Movie movie : movies) {
System.out.println(movie);
}
Collections.sort(movies);
System.out.println("After....");
for (Movie movie : movies) {
System.out.println(movie);
}
}
public static class Movie implements Comparable<Movie> {
private int id;
private String name;
private String directory;
private double rating;
public Movie(int id, String name, String directory, double rating) {
this.id = id;
this.name = name;
this.directory = directory;
this.rating = rating;
}
public int getId() {
return id;
}
public String getDirectory() {
return directory;
}
public String getName() {
return name;
}
public double getRating() {
return rating;
}
#Override
public int compareTo(Movie o) {
int diff = (int) asInt(getRating()) - asInt(o.getRating());
if (diff == 0) {
diff = getName().compareTo(name);
}
return diff;
}
protected int asInt(double value) {
String text = Double.toString(value);
text = text.replaceAll("\\.", "");
return Integer.parseInt(text);
}
#Override
public String toString() {
return getId() + ", " + getName() + ", " + getDirectory() + ", " + getRating();
}
}
}
You need to read this input file one line at a time, parse each line by splitting at ',', constructing a Movie object (that you define) and adding to some kind of array / map / set. Then sort your array / map / set according to the instructions, and write out the response file.
Do some research into:
reading lines from files
parsing strings using split
lists, maps
sorting (compare)
OK, an answer has been accepted, but I have the right not to have the same opinion.
Comparable should reflect the relationship between 2 objects based on their entire state(of course, ids and other irrelevant fields are skipped). If you want to order some objects by their partial state(a few fields) you should use a Comparator.

Deleting content and displaying all the content in JAVA

I'm here with my classes, my software is almost done after finishing last two things I will continue to GUI development. Anyway, here is my code:
public class Team
{
private String clubName;
private String preName;
private ArrayList<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<Branch> getBranches() { branches = new ArrayList<Branch>(branches);return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<Branch> branches) { this.branches = new ArrayList<Branch>(branches); }
}
public class Branch
{
public ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() {players =new ArrayList<Player>(players); return players; }
public void setPlayers(ArrayList<Player> players) { this.players =new ArrayList<Player>(players); }
public String toString() {
return "Branches [" + brName + "]";}
}
public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;
public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}
public Player(){}
public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }
public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
public String toString() {
return "Player [name=" + name + ", number=" + number + ", pos=" + pos
+ ", salary=" + salary + "]";
}
}
//TEST
String p1,p2;
int a1,a2;
String t, br;
System.out.print("Enter player name : ");
p1 = input.readLine();
System.out.print("Enter player position : ");
p2 = input.readLine();
System.out.print("Enter player salary : ");
a1 = Integer.parseInt(input.readLine());
System.out.print("Enter player number : ");
a2 = Integer.parseInt(input.readLine());
players[pCount].setName(p1);
players[pCount].setPos(p2);
players[pCount].setSalary(a1);
players[pCount].setNumber(a2);
ptmp.add(players[pCount]);
pCount++;
System.out.print("Enter the branch of player : ");
br = input.readLine();
int fff=0;
for(int i = 0; i<brCount;i++)
{
if(br.equals(myBranch[i].brName)==true){
myBranch[i].setPlayers(ptmp);fff=i;}
}
MY FIRST QUESTION : I'm trying to add a player to my system. When a player added I can easily add it to Branch class too and connect them. But I can't do it for Players' club. I mean I want to display which player plays in which club. But I can't do it.
MY SECOND QUESTION : Deleting a player is problem too. When I delete player it should be deleted everywhere. But couldn't figured that out.
In the test, you can see the display function I tried. It works fine for Branch-Player. And I wanna add Team connection too. Team-Branch-Player should be connected.
Q1: It depends how efficiently you want to do your searches.. for now, since you don't store back references you have to first search in which branch is your player and then search which is the club that contains your branch.
With good equals method for your Branch and Player class this is trivial:
for (Team t : teamList)
{
if (t.branches.contains(player))
return true;
}
return false;
But this won't be efficient since you'll have a O(n*m) complexity where n is the team size and m is the average branch size.
If you want something more efficient I'd suggest you to store backreferences inside your classes, you can have your Player class with two attributes
Branch currentBranch
Team currentTeam
and you can set them while you add the player to a branch/team.
Otherwise you can keep a separate HashMap that maps every player to his branch/team. Less memory efficient but quite straightforward.
Q2: to remove the Player from his branch/team you just have to know in which one he stays.. (using the answer to Q1), then before removing from players you just remove it from the corresponding branch/team:
Branch b = findWhichBranch(player);
Team t = findWhichTeam(player);
b.remove(player);
t.remove(player);
players[index] = null;
Of course if branch is implied by team you will just remove it from the branch, since there's no direct association between a player and a team.

Categories