I'm having some difficulty adding an arrayList of user details to another arrayList which contains details of each user i create.
I have 2 classes: addUser and Database.
In the addUser class i have the following code:
JLabel submitButton = new JLabel("Submit: ");
contentPane.add(submitButton);
JButton addUser = new JButton("+ Add User");
addUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
addToArray();
databaseArray.add(app);
frame.dispose();}});
contentPane.add(addUser);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
//arraylist of details for a single applicant
final ArrayList<String> app = new ArrayList<String>();
public void addToArray()
{
appNumber = appNumberField.getText();
name = nameField.getText();
date = dateField.getText();
fileLoc = fileLocField.getText();
country = countryRefField.getText();
app.add(appNumber);
app.add(name);
app.add(date);
app.add(fileLoc);
app.add(country);
}
in the database class i have the following code:
public class Database
{
public ArrayList<ArrayList> applicants;
/**
* Constructor for objects of class Database
*/
public Database()
{
applicants = new ArrayList<ArrayList>();
}
/**
* adds a new applicant to the database
*/
public void addApplicant(ArrayList app)
{
applicants.add(app);
}
public void list()
{
int n = applicants.size();
for(int i = 0; i < n ; i++)
System.out.println(applicants.get(i));
}
}
However when i add a user from the addUser class it does not appear when i use the list method in the Database class.
Any help would be appreciated.
Thanks.
import java.util.ArrayList;
public class Store {
int appNumber;// = appNumberField.getText();
String name;// = nameField.getText();
int date;// = dateField.getText();
boolean fileLoc;// = fileLocField.getText();
String country;// = countryRefField.getText();
public Store(int appNumbe, String nam, int dat, boolean fileLo,
String countr) {
appNumber = appNumbe;
name = nam;
date = dat;
fileLoc = fileLo;
country = countr;
}
public static void main(String[] args) {
ArrayList<Store> app = new ArrayList<Store>();
app.add(new Store(22, "Name", 2, false, "India"));
}
}
I think you should try something like this to store data . It will be easy to insert and retrive .
Related
I had this object oriented programming project last semester and it was all about simulating a simple dormitory.
1.There should have been a manager class in which the main method and like 80 percent of the other methods had to be there.
2.A dormitory class containing an arraylist of blocks.
3.A block class containing an arraylist of rooms.
4.A room class containing an arraylist of students.
5.All of these classes contained getters and setters for their private variables.
There were a few methods that we should've added to the program which has nothing to do with my question,so I will not write them in here,but the thing is,a few of theses methods needed to look through these arraylists to find a specific object.For example,a student with a specific student number.I created these methods with nested loops.But I know there is some way I could avoid heavy nesting.
Here is my reduced code.I will only let the manager class contain one nested loop method as an example:
import java.util.Scanner;
public class Manager {
private String name;
private String familyName;
private String userName;
private String passWord;
private static Scanner scan = new Scanner(System.in);
private Dormitory dorm = new Dormitory();
private static Menu menu = new Menu();
private Student tempStudent;
private Block tempBlock;
private Room room;
private boolean bool;
{
dorm.setDormManager(this);
}
public Manager(String managerName, String managerID) {
name = managerName;
userName = managerID;
}
//find student with its number
public void findStudent() {
//Taking the student number from the user.
System.out.println("Please enter the student number:");
String studentNum = scan.nextLine();
for (int i = 0; i < dorm.getBlockList().size(); i++)
for (int j = 0; j < dorm.getBlockList().get(i).getRooms().size(); j++)
for (int k = 0; k < dorm.getBlockList().get(i).getRooms().get(j).getRoomStudents().size(); k++)
if (dorm.getBlockList().get(i).getRooms().get(j).getRoomStudents().get(k).getStudentNumber().equals(studentNum)) {
tempStudent = dorm.getBlockList().get(i).getRooms().get(j).getRoomStudents().get(k);
break;
}
}
public void create() {
//Used loops for the original program.
Block block1 = new Block("1");
Block block2 = new Block("2");
dorm.getBlockList().add(block1);
dorm.getBlockList().add(block2);
Room room1 = new Room("1");
Room room2 = new Room("2");
dorm.getBlockList().get(0).getRooms().add(room1);
dorm.getBlockList().get(1).getRooms().add(room2);
Student student1 = new Student("12345678");
Student student2 = new Student("98765432");
dorm.getBlockList().get(0).getRooms().get(0).getRoomStudents().add(student1);
dorm.getBlockList().get(1).getRooms().get(0).getRoomStudents().add(student2);
}
public static void main(String[] args) {
Manager manager = new Manager("Dumbledore", "#1112");
manager.create();
}
}
public class Dormitory {
private int blocks;
private Manager dormManager;
private long allMembers;
private ArrayList<Block> blockList = new ArrayList<Block>();
}
public class Block {
private String blockNumber;
private ArrayList<Room> rooms = new ArrayList<Room>();
private Dormitory dorm = new Dormitory();
public Block(String blockNum) {
blockNumber = blockNum;
}
}
public class Room {
private String roomNumber;
private ArrayList<Student> roomStudents = new ArrayList<Student>();
private Block roomBlock;
private Student roomManager;
public Room(String roomNum) {
roomNumber = roomNum;
}
}
public class Student {
private String studentName;
private String studentFamilyName;
private String studentNumber;
private Room room;
public Student(String studentNum) { //Creates a student object using the student number.
studentNumber = studentNum;
}
}
I tried my best to reduce the code.
I searched a lot and asked a lot of people about this but I didn't get my desired answer.I'm not sure why I couldn't find anything about this,but I'd really appreciate it if you'd lend me a hand or give me the link of a related article.
Short answer: No, you should never loop through everything checking for getStudentNumber().equals(studentNum). This has linear time complexity O(N)
Long answer: You should index your data based on your queries
Eg: Indexing with HashMaps which have constant time complexity O(1). (Note: This code is not thread safe)
public class SchoolService {
private Map<String, Student> studentsById = new HashMap<>();
private Map<Long, Dorm> dormsById = new HashMap<>();
/// dormsByAreaCode is showing an example of an index which groups objects into lists
private Map<String, List<Dorm>> dormsByAreaCode = new HashMap<>();
public void addStudent(Student student) {
if (studentsById.containsKey(student.getName()) {
throw new IllegalStateException("Duplicate student " + student.getName());
}
studentsById.put(student.getId(), student);
}
public Student getStudentById(String studentId) {
Student student = studentsById.get(studentId);
if (student == null) {
throw new IllegalStateException("No such student " + studentId);
}
return student;
}
public void addDorm(Dorm dorm) {
// TODO: validation
dormsById.put(dorm.getId(), dorm);
List<Dorm> areaDorms = dormsByAreaCode.get(dorm.getAreaCode());
if (areaDorms == null) {
areaDorms = new ArrayList<>();
dormsByAreaCode.put(dorm.getAreaCode(), areaDorms);
}
areaDorms.add(dorm);
}
public Dorm getDormById(long dormId) {
Dorm dorm = dormsById.get(id);
// TODO: validation
return dorm;
}
public List<Dorm> getDormsByAreaCode(String areaCode) {
List<Dorm> areaDorms = dormsByAreaCode.get(areaCode);
// TODO: validation
return areaDorms;
}
// etc
}
The following quote is from tutorialspoint. This is the perfect use case of the forEach method from the Stream interface. The link I provided and further reading on Streams can help avoid repetitive code.
Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone.
dorm.getBlockList().stream().forEach((b) -> {
b.getRooms().stream().forEach((r) -> {
...
})
});
You can also read about parallelStreams from here.
This question already has answers here:
Avoiding overwriting objects in ArrayList
(2 answers)
Closed 3 years ago.
The data which was previously stored in an array list , is getting replaced by updated data.
code is shown below
public class Telivision {
private String tvBrand;
private Double tvCost;
private Integer tvDimension;
private String tvScreen;
public String getTvBrand() {
return tvBrand;
}
public void setTvBrand(String tvBrand) {
this.tvBrand = tvBrand;
}
public Double getTvCost() {
return tvCost;
}
public void setTvCost(String brand) {
if(this.tvBrand.equalsIgnoreCase("Samsung")){
this.tvCost = 100*1.5;
}else if(this.tvBrand.equalsIgnoreCase("Sony")){
this.tvCost = 100*2.0;
}
}
public Integer getTvDimension() {
return tvDimension;
}
public void setTvDimension(Integer tvDimension) {
this.tvDimension = tvDimension;
}
public String getTvScreen() {
return tvScreen;
}
public void setTvScreen(String tvScreen) {
this.tvScreen = tvScreen;
}
#Override
public String toString() {
return "Telivision [tvBrand=" + tvBrand + ", tvCost=" + tvCost + ", tvDimension=" + tvDimension + ", tvScreen="
+ tvScreen + "]";
}
TESTER IS AS SHOWN BELOW
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
telivision.setTvBrand("Sony");
telivision.setTvDimension(36);
telivision.setTvScreen("Led");
telivision.setTvCost("Sony");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
}
the output which is expected is as shown below
[Telivision [tvBrand=SAMSUNG, tvCost=150.0, tvDimension=40, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
but the output observed is as shown below
[Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
kindly let me know what mistake i am doing in this code
You're list is not being overwritten. You are are adding the same instance of the class twice instead of creating a new one with the new attributes. Because the original istance changed you get the same attributes for both entries in the list. Create a new instance of the object for each Television you add to the list.
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision secondTelivision = new Telivision();
secondTelivision.setTvBrand("Sony");
secondTelivision.setTvDimension(36);
secondTelivision.setTvScreen("Led");
secondTelivision.setTvCost("Sony");
telList.add(secondTelivision);
System.out.println(telList);
}
You forgot to declare a second Telivision to separate the two.
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision television2 = new Television();
telivision2.setTvBrand("Sony");
telivision2.setTvDimension(36);
telivision2.setTvScreen("Led");
telivision2.setTvCost("Sony");
telList.add(telivision2);
System.out.println(telList);
System.out.println(telivision2.getTvBrand()+"Cost is "+telivision2.getTvCost());
//telList.addAll(telList);
//System.out.println(telList);
}
}
Also “Telivision” is actually spelled Television
I have class which initiates an arraylist of type String. I then add some dummy data into this array.
public class Main {
public static void main(String[] args)
{
Home h = new Home();
h.add();
}
}
public class Home
{
public ArrayList<String> Group_Customers= new ArrayList<String>();
public void add()
{
String[] group1 = {"0", "Mr", "Smith", "Andrew"}
for(int i = 1; i < group1.length; i++)
{
Group_Customers.add(group1[i]);
}
Add_Booking a = new Add_Booking();
a.Add();
}
}
In a seperate class. I then call this arraylist and add more data to it. However the array is empty in this different class
public class Add_Booking
{
String Title;
String Firstname;
String Surname;
public void add_Data
{
Title = "Mr";
Firstname = "Bob";
Surname = "Gallow";
save_Data();
}
public void save_Data
{
Home h = new Home();
String[] responses = {Title, Firstname, Surname};
for(int i = 1; i < responses.length; i++)
{
h.Group_Customers.add(responses[i]);
}
System.out.println(h.Group_Customers);
}
}
--Outputs responses without group1 test from class Home.
Am I refering to Group_Customers wrong within this different class?
All help appreciated.
Thanks
When calling Home h = new Home(); you instantiate a new Home with the default constructor.
Make sure you add the dummy data in the constructor if you want the array to contains data. Also, the actual code would not compile, you can't just throw method call in class body.
You would have something like this :
public class Home
{
//Declare the List
public ArrayList<String> Group_Customers = null;
//Default constructor
public Home()
{
//Instantiate and add dummy data
Group_Customers = new ArrayList<String>();
Group_Customers.add("test");
}
}
public class Add_Booking
{
public static void main(String args[])
{
//Construct a new home with default constructor.
Home h = new Home();
//Add new data
h.Group_Customers.add("new data");
//Display List content (should display test and new data)
System.out.println(h.Group_Customers);
}
}
Note that by convention, variable should start with a lower-case and an upper-case at each words so you should rename your variable as groupCustomers.
I am having difficulty getting information from a jList so that it can be used to create an object in a different class when a button is clicked,
private void jButtonAddOrderActionPerformed(java.awt.event.ActionEvent evt) {
int noCopies;
String title, Name;
noCopies = Integer.parseInt(jTextFieldCopies.getText());
title = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getName();
Name = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getPublisherName();
new Order(noCopies, title, Name);
setjlistmodel(Order.orderItem);
I am sure there are no problems with my setjlistmodel method as this works elsewhere in my program when only getting information from text fields. I think my problem is with these two lines:
title = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getName();
Name = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getPublisherName();
}
This is my order class;
package bookstore;
import java.util.ArrayList;
public class Order {
int noOfBooks;
String bookTitle;
String pubName;
public static ArrayList<Order> orderItem = new ArrayList<>();
ArrayList<ArrayList<Order>> Order = new ArrayList<>();
public Order(int noBooks, String Title, String Name)
{
this.noOfBooks = noBooks;
this.bookTitle = Title;
this.pubName = Name;
orderItem.add(this);
}
public void addOrder(ArrayList ord)
{
Order.add(ord);
}
public int getNoBooks()
{
return noOfBooks;
}
public String getBookTitle()
{
return bookTitle;
}
public String getPubName()
{
return pubName;
}
}
setjlistmodel method:
private void setjlistmodel(ArrayList<Order> orderInstances){
DefaultListModel OrderList = new DefaultListModel();
for(int i = 0; i<=OrderList.size()-1;i++){
OrderList.addElement(orderInstances.get(i).getNoBooks());
System.out.println(orderInstances.get(i).getBookTitle());
System.out.println(OrderList.firstElement());
}
jListOrder.setModel(OrderList);
}
The problem is that it is not displaying anything in jListOrder when the button is clicked. I don't think the Order is being added to the orderItem ArrayList.
"The problem is that it is not displaying anything in jListOrder when the button is clicked. I don't think the Order is being added to the orderItem ArrayList."
I think adding an orderItem is fine.
OrderList size is zero when you first initialize it, which means your loops does absolutely nothing
DefaultListModel OrderList = new DefaultListModel();
for(int i = 0; i <= OrderList.size() - 1; i++)
You probably want
for(int i = 0; i <= orderInstances.size() - 1; i++)
Which is using the ArrayList size.
As a side note, please separate operators with space. It makes it easier to read.
I've been stuck at a seemingly simple problem for hours and I just can't find the solution. I'm trying to implement a very simple Forum in Java and I'm trying to load the entrys at the moment.
My forum is a JList that is filled with JPanels and that accepts entries via the JLists DefaultListModel and the addMessage method. So if I add an entry without the database it looks like this:
MessageList m = new MessageList();
m.addMessage("NAME AUTOR", "<html><body style='width: 675px;'>Lorem ipsum dolor sit amet.", "22.01.13", "SOA");
The messageList class looks like this:
public class MessageList extends JList{
DefaultListModel messageModel = new DefaultListModel();
MessageRenderer messageRenderer = new MessageRenderer();
public MessageList( ){
this.setCellRenderer(messageRenderer);
this.setModel(messageModel);
}
public void addMessage(String author, String text, String date, String tag){
messageModel.addElement(new Message(author, text, date, tag));
}
}
I've also written the Code for getting an ArrayList (called allBtr) with the Message Objects (called ConBeitrag) from the database:
ArrayList<ConBeitrag> allBtr = new ArrayList<ConBeitrag>();
ConBeitrag conBtr = new ConBeitrag();
try {
allBtr = conBtr.getAllBtr();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The message objects look like this:
public class ConBeitrag {
private int beitragid;
private int projektid;
private int mitarbeiterid;
private String beitragText;
private String erstellt_am;
private String geaendert_am;
private String schlagwort1;
private String schlagwort2;
private MdBeitrag mdBtr = new MdBeitrag();
public ConBeitrag (){
}
public ConBeitrag(int beitragid, int projektid, int mitarbeiterid, String beitragText, String erstellt_am, String geaendert_am){
this.beitragid = beitragid;
this.projektid = projektid;
this.mitarbeiterid = mitarbeiterid;
this.erstellt_am = erstellt_am;
this.geaendert_am = geaendert_am;
this.beitragText = beitragText;
this.schlagwort1 = schlagwort1;
this.schlagwort2 = schlagwort2;
}
public ArrayList<ConBeitrag> getAllBtr() throws SQLException{
MdBtrInterface modInt;
modInt = new MdBeitrag();
ArrayList<ConBeitrag> AlBtr = modInt.getAllBtr();
for(ConBeitrag object: AlBtr){
System.out.println(object.beitragText);
}
return AlBtr;
}
}
Now what would be the smartest way to get the ArrayList into a form that I can pass into the addMessage method? I've kind of approached this from the GUI end, then from the database end, and now I'm stuck in the middle.
Overwritten toString() method:
#Override
public String toString() {
return mitarbeiterid + beitragstext + erstellt_am + schlagwort1 + schlagwort2;
}
"The messages are stored inside the ArrayList as Objects if that helps. So if I run "System.out.println(allBtr);" it gives me "[ConBeitrag#48f4104f, ConBeitrag#f5ad7f4, ConBeitrag#1517dc0c]"
You need to override the toString method in your ConGeitrag class. Something like this.
public class ConBeitrag {
...
#Override
public String toString(){
return author + ", " + text + ", " + date + ", " + tag;
}
}
You can make the return any format you want. Test this one out and make changes as desired to the format.
Try this out as a Helper method (after you've overridden the toString)
public JList createJList(ResultSet rs){
DefaultListModel model = new DefaultListModel();
while (rs.next()){
String author = rs.getString("author"); // Just an example. You may
String text = rs.getString("text"); // need to retrieve your
String date = rs.getString("date"); // data differently
String tag = rs.getString("tag");
Message message = new Message(author, text, date, tag);
model.addElement(message);
}
JList list = new JList(model);
return list;
}
I don't really see a need for a Custom JList for this situation.
Test run: output : 3testtestnullnull. Besides the formatting, it works fine
public class ConBeitragTest {
public static void main(String[] args) {
ConBeitrag con = new ConBeitrag(1, 2, 3, "test", "test", "test");
System.out.println(con);
}
}
class ConBeitrag {
private int beitragid;
private int projektid;
private int mitarbeiterid;
private String beitragText;
private String erstellt_am;
private String geaendert_am;
private String schlagwort1;
private String schlagwort2;
public ConBeitrag() {
}
public ConBeitrag(int beitragid, int projektid, int mitarbeiterid, String beitragText, String erstellt_am, String geaendert_am) {
this.beitragid = beitragid;
this.projektid = projektid;
this.mitarbeiterid = mitarbeiterid;
this.erstellt_am = erstellt_am;
this.geaendert_am = geaendert_am;
this.beitragText = beitragText;
this.schlagwort1 = schlagwort1; // This is null
this.schlagwort2 = schlagwort2; // This is null
}
#Override
public String toString() {
return mitarbeiterid + beitragText + erstellt_am + schlagwort1 + schlagwort2;
}
}