Adding An Object Onto ArrayList Between Two Classes - java

I'm trying to add order1 object to orderList in the Customer class, but it's not working. The toString() method returns zero items in the ArrayList. Does anyone have any idea of what else I can try doing instead?
public class Customer {
private ArrayList<Order> orderList;
private int numberOfOrders = 0;
public Customer(String name, Order firstElementInList) {
this(name);
this.orderList.add(0, firstElementInList);
}
public void setNumberOfOrders() {
this.numberOfOrders = orderList.size();
}
public String toString() {
return name + numberOfOrders;
}
}
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Order order1 = new Order( "bob", 1.1 );
Customer bob = new Customer( "Bobby Shmurda ", order1 );
System.out.println(bob.toString());
}
}
A String Object gets added to ArrayList and when toString() is invoked should return the length of the ArrayList.

Because your list is yet to be created as you have not created its object.
Use below code to create your list.
private ArrayList<Order> orderList = new ArrayList<>();

public class Customer {
private List<Order> orderList;
private int numberOfOrders = 0;
public Customer(String name, Order firstElementInList) {
this(name);
if(orderList == null) {
orderList = new ArrayList<Order>();
}
this.orderList.add(0, firstElementInList);
}
public void setNumberOfOrders() {
this.numberOfOrders = orderList.size();
}
public String toString() {
return "The length of the orderList: " + orderList != null ? orderList.size() : 0;
}
}
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Order order1 = new Order( "bob", 1.1 );
Customer bob = new Customer( "Bobby Shmurda ", order1 );
System.out.println(bob.toString());
}
}

Related

Adding array of object into array list and compare with other array list based on one property value and filter the result

Adding array of object into array list and compare with other array list based on one property value and filter the result.
I have an array of object personDetails and departmentDetails.
package com.education;
import java.util.*;
public class educationMain {
public static void main(String[] args) {
List<person> list=new ArrayList<person>();
person l1 = new person(1,"Samual",100,"Sales","Business");
person l2 = new person(2,"Alex",100,"Sales","Business");
person l3 = new person(3,"Bob",101,"Engineering","Technology");
person l4 = new person(4,"Michel",101,"Engineering","Technology");
person l5 = new person(5,"Ryan",102,"PR","Services");
person l6 = new person(6,"Horward",103,"Leadership","Managmnet");
person l7 = new person(7,"Cyna",104,"HR","Human Resource");
list.add(l1);
list.add(l2);
list.add(l3);
list.add(l4);
list.add(l5);
list.add(l6);
list.add(l7);
for(person b:list){
System.out.println(b.personId+" "+b.name+" "+b.deptCode+" "+b.parentDept+" "+b.deptName);
}
List<department> depList = new ArrayList<department>();
department d1 = new department(100, "Sales","Business");
department d2 = new department(101, "Engineering","Technology");
department d3 = new department(102, "PR","Services");
depList.add(d1);
depList.add(d2);
depList.add(d3);
for(department b:depList){
System.out.println(b.deptCode+" "+b.parentDept+" "+b.deptName);
}
}
}
So above code is working fine and displaying correctly.
My person class
package com.education;
public class person {
public int personId;
public String name;
private int deptCode;
private String parentDept;
private String deptName;
public person(int personId, String name, int deptCode, String parentDept, String deptName) {
super();
this.personId = personId;
this.name = name;
this.deptCode = deptCode;
this.parentDept = parentDept;
this.deptName = deptName;
}
public void display(){
System.out.println(" " + personId + " " +name + " " + deptCode+ " " + parentDept + " "+deptName);
System.out.println();
}
}
My department class
public class department {
private int deptCode;
private String parentDept;
private String deptName;
public department(int deptCode, String parentDept, String deptName) {
super();
this.deptCode = deptCode;
this.parentDept = parentDept;
this.deptName = deptName;
}
public void dispalyDepartment() {
System.out.println(" "+deptCode+" "+parentDept+" "+deptName);
}
}
Now My goal is personDetails and departmentDetailsinto arraylist and compare and then findout the diference one bsed on dept code.
Here is my Logic : which is working fine.
List<person> listC = new ArrayList<person>();
for(person p : list) {
boolean flag = false;
for (department d:depList) {
if(p.deptCode == d.deptCode) {
flag = false;
break;
}else {
flag = true;
}
}
if(flag == true) {
listC.add(p);
}
}
o/p should be like
(6,"Horward",103,"Leadership","Managmnet");
(7,"Cyna",104,"HR","Human Resource");
because deptCode : 103 and 104 is not present.
Can anybody help me here. Can I use any other collection technique.
Try this.
Set<Integer> deptCodes = Arrays.stream(departmentDetails)
.map(department -> department.deptCode)
.collect(Collectors.toSet());
List<person> persons = Arrays.stream(personDetails)
.filter(person -> !deptCodes.contains(person.deptCode))
.collect(Collectors.toList());
persons.forEach(person -> person.display());
output:
6 Horward 103 Leadership Managmnet
7 Cyna 104 HR Human Resource

Creating an printing an object that stores strings and integers in java

I have the following problem. Five classes are interacting with each other. Two of theme are doing fine. But with the creating of an Object of one class (Ticket) in my main class Event (getting user input from another class (UserInput), an processing this in the costructor) i have now problem to display the results.
Main class Event with main methode
import java.util.ArrayList;
public class Event {
private static String artistName;
private static int artistSalary;
private Language language;
private static ArrayList<String> trackList;
private InputReader inputReader;
private Ticket ticket;
private int amountOfTicketCategories;
private static Object[] ticketList;
private static int index;
public Event() {
}
public Event(Artist artist, Ticket ticket) {
artistName = artist.getArtistName();
artistSalary = artist.getArtistSalary();
trackList = artist.getArrayList();
for (index = 0; index < amountOfTicketCategories; index++) {
ticketList[index] = ticket.getTicket();
ticketList[index].toString();
}
}
public void chooseWhatToDefine() {
language = new Language();
language.whatToSpecify();
}
public void setTicketPrice(String ticketCategory, int ticketPrice) {
}
public void displayArtist(String artistName, int artistSalary) {
language = new Language();
language.displayArtistAndSalary(artistName, artistSalary);
}
public void displayTracklist(ArrayList<String> trackList) {
language = new Language();
language.displayTrackList(trackList);
}
public void displayTickets(Object[] ticketList) {
language = new Language();
language.displayTicket(ticketList);
}
public static void main(String[] args) {
Event event1 = new Event(new Artist(), new Ticket());
event1.displayArtist(artistName, artistSalary);
event1.displayTracklist(trackList);
event1.displayTickets(ticketList);
}
}
Ticket class with constructor that initalize the class with the user input comming from the InputReader class, and creates an object of Strings and Integers.
import java.util.Arrays;
public class Ticket {
private static String ticketCategory;
private static int ticketAmount;
private static int ticketPrice;
private InputReader inputReader;
private int amountOfTicketCategories;
private int index;
private Ticket[] ticketList;
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
}
public Ticket() {
inputReader = new InputReader();
inputReader.specifyTicketCategories();
ticketList = new Ticket[amountOfTicketCategories];
for (index = 0; index < amountOfTicketCategories; index++) {
inputReader.specifyTicket(ticketCategory, ticketAmount, ticketPrice);
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
}
}
public String toString() {
return("TicketCategory: " + ticketCategory + "Amount of Tickets: " + ticketAmount + "Ticket Price: " +ticketPrice);
}
public Object getTicket() {
return ticketList[index];
}
public int getAmountOfTicketCategories() {
amountOfTicketCategories = inputReader.specifyTicketCategories();
return amountOfTicketCategories;
}
}
InptReader class that processes the user input:
import java.util.ArrayList;
import java.util.Scanner;
public class InputReader {
private Scanner sc;
private Language language;
private ArrayList <String> tracks;
public InputReader() {
tracks = new ArrayList<String>();
language = new Language();
sc = new Scanner(System.in);
}
public int specifyTicketCategories() {
language.defineAmountOfTicketCategories();
return sc.nextInt();
}
public void specifyTicket(String ticketCategory, int ticketAmount, int ticketPrice) {
language.specifyTicketCategory();
ticketCategory = sc.next();
language.specifyTicketAmount();
ticketAmount = sc.nextInt();
language.specifyTicketPrice();
ticketPrice = sc.nextInt();
}
public int amountOfTickets() {
return sc.nextInt();
}
public int ticketPrice() {
return sc.nextInt();
}
public String readName() {
language.specifyArtist();
return sc.nextLine();
}
public int readInteger() {
language.specifyArtistSalary();
return sc.nextInt();
}
public void addTitle() {
int anzahlSongs = 3;
int index = 0;
while (index < anzahlSongs) {
language.specifyTrackList();
tracks.add(sc.nextLine());
index++;
}
}
public ArrayList<String> getArray() {
return tracks;
}
}
Language class that consists of the language statements
import java.util.ArrayList;
public class Language {
public Language () {
}
public void whatToSpecify() {
System.out.println("What would you like to specify fist? For Artist press 1, for Ticket press 2");
}
public void specifyArtist() {
System.out.println("Who is the artist? ");
}
public void specifyArtistSalary() {
System.out.println("How much does the artist earn? ");
}
public void displayTicket(Object[] ticketList) {
System.out.println("Ticketlist: " + ticketList);
}
public void displayArtistAndSalary(String artistName, int artistSalary) {
System.out.println("Artist: " + artistName + " " + "Salary: " + artistSalary);
}
public void displayTrackList(ArrayList<String> trackList) {
System.out.println("Tracklist: " + trackList);
}
public void specifyTicketCategory() {
System.out.println("What is the ticket category? ");
}
public void specifyTicketAmount() {
System.out.println("What ist the amount of tickets? ");
}
public void specifyTicketPrice() {
System.out.println("What is the price for your ticket?");
}
public void specifyTrackList() {
System.out.println("Add title: ");
}
public void defineAmountOfTicketCategories() {
System.out.println("How many ticket categories you like to set up?");
}
public void line() {
System.out.println("***********************************");
}
}
Artist class that that has creates an instance of an artist in the main class (same idea as for ticket) but with other variables and parameters.
import java.util.ArrayList;
public class Artist {
private int artistSalary;
private String artistName;
private InputReader inputReader;
ArrayList <String> trackList;
public Artist() {
inputReader = new InputReader();
artistName = inputReader.readName();
artistSalary = inputReader.readInteger();
inputReader.addTitle();
trackList = inputReader.getArray();
trackList.remove(2);
}
public String getArtistName() {
return artistName;
}
public int getArtistSalary() {
return artistSalary;
}
public ArrayList<String> getArrayList(){
return trackList;
}
}
Output in the console:
Add title:
Hello
Add title:
Hello
How many ticket categories you like to set up?
5
Artist: David Salary: 5000
Tracklist: [, Hello]
Ticketlist: null
First of all, in the Ticket class's constructor, you use the other constructor (The one with the 3 arguments), which has an empty body.
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
//this is empty
}
That means you're creating an object with.. nothing in it (null variables).
Try this:
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
this.ticketCategory = ticketCategory;
this.ticketAmount = ticketAmount;
this.ticketPrice = ticketPrice;
}
Then, your getTicket method is wrong. You never define the "index" integer in your Ticket class.
public Object getTicket() {
return ticketList[index];
}
Where "index" is undefined.
The ticketList should not be in the Ticket class => each time you create a Ticket instance, it will probably not be the same as the previous one.

Java Code Overwrites Previous Entries of New Object Into Queue Array

I am trying to write an algorithm that allows the user of the program to enter an order into a queue that is an array. I am able to insert the order and insert another order, however, every subsequent order I place overwrites my previous orders. There are still spots in the array where the orders were but they are all copies of the newest order. Here is my code:
//Class to define individual orders for queueOrders
class Order
{
//Global Variables
public static String name;
public static String order;
public static int orderNum;
//Constructor
public Order()
{
}
public Order(int orderNum)
{
this.orderNum = orderNum;
}
public Order(String name, String order)
{
this.name = name;
this.order = order;
}
public Order(String name, String order, int orderNum)
{
this.name = name;
this.order = order;
this.orderNum = orderNum;
}
//Getters and Setters
public static String getName()
{
return name;
}
public static void setName(String name)
{
Order.name = name;
}
public static String getOrder()
{
return order;
}
public static void setOrder(String order)
{
Order.order = order;
}
public static int getOrderNum()
{
return orderNum;
}
public static void setOrderNum(int orderNum)
{
Order.orderNum = orderNum;
}
}
//Class to define queue
class QueueOrders
{
//Global Variables
// private int nItems = 0;
private static int maxSize;
private static int numOfOrders = 0;
//Array of Orders objects
private static Order orders[];
private static int front;
private static int back;
//Constructor
public QueueOrders(int size)
{
maxSize = size;
orders = new Order[maxSize];
front = 0;
back = 0;
}
//Insert new order
public static void insertOrder(String name, String order)
{
//Variables
// int cntr = 1;
if(isFull())
{
System.out.println("There are too many orders."
+ " Remove some first. ");
}
else
{
// if(back == maxSize - 1)
// {
// back = 0;
// }
Order.setName(name);
Order.setOrder(order);
//// Order.name = name;
//// Order.order = order;
// Order.setOrderNum(cntr);
Order newOrder = new Order(name, order, (numOfOrders + 1));
//Add order to orders array
orders[back] = newOrder;
//front = numOfOrders - 1;
// cntr++;
back++;
numOfOrders++;
}
}
//These functions are in the main class of the program
public static void main(String[] args)
{
QueueOrders queue = new QueueOrders(100);
menu();
}
//Function to add an order to the queue
public static void addOrder()
{
//Variables
String xName;
String xOrders;
Scanner myScan = new Scanner(System.in);
try
{
//Message user
System.out.println("What is the three letter name for your order? ");
xName = myScanner.nextLine();
//Message user
System.out.println("What is your order? ");
xOrders = myScan.nextLine();
QueueOrders.insertOrder(xName, xOrders);
QueueOrders.displaySingleOrder();
System.out.println("Your order has been placed. ");
} catch (Exception e)
{
System.out.println("Was unable to insert your order");
}
}
The problem is that you are using static variables for order data:
public static String name;
public static String order;
public static int orderNum;
They are specific to class Order, not to objects Order order you are adding in the list. Remove the keyword static from those variables.
This implementation
public class Sample {
public String a;
public static String b;
public static void main(String[] args) {
Sample s1 = new Sample();
s1.a = "1a";
s1.b = "1b";
Sample s2 = new Sample();
s2.a = "2a";
s2.b = "2b"; // This one set Sample.b to "2b" because b is
// static and shared among all Sample objects (s1 and s2).
System.out.println(s1.a + " " + s1.b + " " + s2.a + " " + s2.b);
}
}
will print 1a 2b 2a 2b (not 1a 1b 2a 2b) because b is static and value "1b" is overwritten by s2.b = "2b".
See this article for more information.

How to access java class member in instance with a string

I have a small class with some data, called MyData:
public class MyData {
public String name = "";
public String nameonly = "";
public int id = 0;
public double earn = 0;
public double paid = 0;
....
public MyData(String name, String nameonly, int id) {
this.name = name;
this.nameonly = nameonly;
this.id = id;
}
}
Then I have a class with arrays of this class for specific type of people called AllMyData:
public class AllMyData {
public ArrayList<MyData> cli = new ArrayList<>();
public ArrayList<MyData> sub = new ArrayList<>();
public ArrayList<MyData> emp = new ArrayList<>();
public ArrayList<MyData> exp = new ArrayList<>();
public ArrayList<MyData> oex = new ArrayList<>();
public ArrayList<MyData> bin = new ArrayList<>();
public ArrayList<MyData> ven = new ArrayList<>();
....
}
in main class I need to add new items to specific array (if id does not exists) where I have a string representative of AllMyData array
public AllMyData elems = new AllMyData();
public void initArray(int id, String name, String tip) {
//this is an example just for "cli" element and "cli" is in String tip
if (!checkForId(elems.cli, id)) {
MyData element = new MyData(name, name, id);
elems.cli.add(element);
}
}
private boolean checkForId(ArrayList<MyData> a, int id) {
for (MyData e : a) {
if (e.id == id) return true;
}
return false;
}
Then I need just a call, for example:
initArray(5, "Test", "emp");
and would like to avoid switch statement and to repeat code for every single type. In this call, "emp" would be element elems.emp
Is there a way to access elems member with a string name instead of creating switch statement?
Create a map of lists in AllMyData instead.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
AllMyData data = new AllMyData();
data.add("foo", new MyData("Hello World", "", 1));
data.add("cli", Arrays.asList(new MyData("BASH", "", 2), new MyData("SHELL", "", 3)));
System.out.println(data);
}
}
AllMyData [map={cli=[MyData [name=BASH, nameonly=, id=2, earn=0.0, paid=0.0], MyData [name=SHELL, nameonly=, id=3, earn=0.0, paid=0.0]], sub=[], oex=[], bin=[], foo=[MyData [name=Hello World, nameonly=, id=1, earn=0.0, paid=0.0]], emp=[], exp=[], ven=[]}]
import java.util.*;
public class AllMyData {
private Map<String, List<MyData>> map;
public AllMyData() {
map = new HashMap<String, List<MyData>>();
map.put("cli", new ArrayList<>());
map.put("sub", new ArrayList<>());
map.put("emp", new ArrayList<>());
map.put("exp", new ArrayList<>());
map.put("oex", new ArrayList<>());
map.put("bin", new ArrayList<>());
map.put("ven", new ArrayList<>());
}
public void add(String key, List<MyData> data) {
List<MyData> list = get(key);
if (list == null) {
map.put(key, data);
} else {
list.addAll(data);
map.put(key, list);
}
}
public void add(String key, MyData data) {
List<MyData> list = get(key);
if (list == null) {
list = new ArrayList<>();
}
list.add(data);
map.put(key, list);
}
public List<MyData> get(String key) {
return map.get(key);
}
#Override
public String toString() {
return String.format("AllMyData [map=%s]", map);
}
}
public class MyData {
public String name = "";
public String nameonly = "";
public int id = 0;
public double earn = 0;
public double paid = 0;
public MyData(String name, String nameonly, int id) {
this.name = name;
this.nameonly = nameonly;
this.id = id;
}
#Override
public String toString() {
return String.format("MyData [name=%s, nameonly=%s, id=%s, earn=%s, paid=%s]", name, nameonly, id, earn, paid);
}
}
Consider the use of a Map from String to ArrayList.
It would look like this:
Map> allMyData = new HashMap<>();

Only the last Object is added to the ArrayList

I created a user defined data type and read data from a file. Here are the codes:
Student Class:
package system.data;
public class Student {
private String firstName;
private String lastName;
private String regNumber;
private int coursework1Marks;
private int coursework2Marks;
private int finalExamMarks;
private double totalMarks;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getRegNumber() {
return regNumber;
}
public void setRegNumber(String regNumber) {
this.regNumber = regNumber;
}
public int getCoursework1Marks() {
return coursework1Marks;
}
public void setCoursework1Marks(int coursework1Marks) {
this.coursework1Marks = coursework1Marks;
}
public int getCoursework2Marks() {
return coursework2Marks;
}
public void setCoursework2Marks(int coursework2Marks) {
this.coursework2Marks = coursework2Marks;
}
public int getFinalExamMarks() {
return finalExamMarks;
}
public void setFinalExamMarks(int finalExamMarks) {
this.finalExamMarks = finalExamMarks;
}
public double getTotalMarks() {
totalMarks = (coursework1Marks * 0.2) + (coursework2Marks * 0.2) + (finalExamMarks * 0.6);
return totalMarks;
}
}
And the main coding:
public class MainInterface extends javax.swing.JFrame {
private File studentFile = new File(".\\StudentMarks.txt");
private PrintWriter printWriter = null;
private FileOutputStream fileOutputStream = null;
public ArrayList<Student> studentDetails = null;
private Scanner input = null;
private int counter = 0;
/**
* Creates new form MainInterface
*/
public MainInterface() {
initComponents();
setLocationRelativeTo(null);
studentDetails = new ArrayList<Student>();
ReadStudentDetails(studentDetails);
}
private void ReadStudentDetails(ArrayList<Student> studentDetails) {
ArrayList<String> strList = new ArrayList<>();
Student student = new Student();
try {
input = new Scanner(studentFile);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainInterface.class.getName()).log(Level.SEVERE, null, ex);
}
while(input.hasNext()){
counter++;
String str = input.nextLine();
strList.add(str);
System.out.println(counter);
}
for (String item : strList) {
int x = 0;
String[] arr = item.split(":");
student.setFirstName(arr[0]);
student.setLastName(arr[1]);
student.setRegNumber(arr[2]);
student.setCoursework1Marks(Integer.parseInt(arr[3]));
student.setCoursework2Marks(Integer.parseInt(arr[4]));
student.setFinalExamMarks(Integer.parseInt(arr[5]));
studentDetails.add(student);
}
}
There no syntax errors given. But When I try to print the elements in the ArrayList as,
for(Student item: studentDetails){
System.out.println(item.getFirstName());
}
It gives out only the last record from the file, (which has 3 records). Why is this happening? Thanks in advance.
The same student object is reused, because Java passes a reference to an object in the call that adds the student to the list. In other words, the original student is passed each time. The solution is to create a new Student for each call.
for (String item : strList) {
int x = 0;
String[] arr = item.split(":");
Student student = new Student();
student.setFirstName(arr[0]);
student.setLastName(arr[1]);
student.setRegNumber(arr[2]);
student.setCoursework1Marks(Integer.parseInt(arr[3]));
student.setCoursework2Marks(Integer.parseInt(arr[4]));
student.setFinalExamMarks(Integer.parseInt(arr[5]));
studentDetails.add(student);
}
create new instance of Student object inside the for loop
like this
for (String item : strList) {
int x = 0;
String[] arr = item.split(":");
Student student = new Student();
student.setFirstName(arr[0]);
student.setLastName(arr[1]);
student.setRegNumber(arr[2]);
student.setCoursework1Marks(Integer.parseInt(arr[3]));
student.setCoursework2Marks(Integer.parseInt(arr[4]));
student.setFinalExamMarks(Integer.parseInt(arr[5]));
studentDetails.add(student);
}
Actually you are always using the same student object.You have to put Student student = new Student(); inside the for loop.
try moving Student student = new Student(); inside the for loop:
for (String item : strList) {
int x = 0;
String[] arr = item.split(":");
Student student = new Student();
student.setFirstName(arr[0]);
student.setLastName(arr[1]);
student.setRegNumber(arr[2]);
student.setCoursework1Marks(Integer.parseInt(arr[3]));
student.setCoursework2Marks(Integer.parseInt(arr[4]));
student.setFinalExamMarks(Integer.parseInt(arr[5]));
studentDetails.add(student);
}
hope this helps.

Categories