This is how the GUI looks
I have a GUI program that stores user's details (such as salary, fname, lname, date) into an arraylist using an add button. After the user presses add, the user presses list to output all the information into a panel.
My full code is below.
public class EmploymentRecords extends javax.swing.JFrame {
ArrayList <Data> Output = new ArrayList <Data>();
Add button:
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
Data d;
String id, firstName, lastName, salary, startDate;
id = txtID.getText();
firstName = txtFName.getText();
lastName = txtLName.getText();
salary = txtSalary.getText();
startDate = txtDate.getText();
d = new Data(id, firstName, lastName, salary, startDate);
Output.add(d);
}
List Button:
private void btnListActionPerformed(java.awt.event.ActionEvent evt) {
String print = "";
for (int i=0; i<=Output.size()-1; i++)
{
print = print + "ID #:" + Output.get(i).id + ", "
+ Output.get(i).firstName + " "
+ Output.get(i).lastName + ", "
+ "$" + Output.get(i).salary + ", "
+ Output.get(i).startDate + "\n ";
}
pnlOutput.setText(print);
}
Remove Button:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
boolean idCheck = Output.contains(id);
if (idCheck == true){
index = Output.indexOf(id);
Output.remove(index);
}
else {
lblError.setText("Employee not found. Please try again.");
}
Data Class:
class Data {
String id, firstName, lastName, salary, startDate;
Data (String _id, String _firstName, String _lastName, String _salary, String _startDate) {
id = _id;
firstName = _firstName;
lastName = _lastName;
salary = _salary;
startDate = _startDate;
}
}
I have everything working such as the list and add button, but my problem is with the Remove button: The user has a button to remove a single employees data from the arraylist based on only writing the the ID in the text area, which also removes all the information outputted to the user in the panel. My code above for the remove button doesnt work and when I press remove, nothing happens and the data stays there in the output panel.
Id really appreciate any help I get on this remove button
This solution uses the streaming API:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
List<Data> elementsWithId = Output.stream() // Use the streaming API on Output
.filter(data -> data.id.equals(id)) // filter out the element(s) with matching id
.collect(Collectors.toList()); // put the findings into a new list
boolean idCheck = (elementsWithId.size() > 0);
if (idCheck == true){
for (Data data: elementsWithId) {
Output.remove(data);
}
}
else {
lblError.setText("Employee not found. Please try again.");
}
// Pass the event on to the list functionality:
btnListActionPerformed(evt);
}
So, the real "magic" happens in the commented lines. You'll search the whole Output list for elements with the given ID and create a new list containing the matches only. (I understood, there should be one at most, but you never know...)
The rest is quite the same as you had it before, just that we're working with the result list here.
Please note, that there are serveral approaches to your problem and this is just one the quick and easy ones. There are more elaborate ones for sure.
Related
I doing a bigger school project (first part of basic objective programming in java - so not touched extended, polyphorism etc yet, thats next part), but run in to a small problem and tried for couple of days to find solution (thru books and internet). I constructed different ArrayLists in one class and different classes (at least two) should get access to them.
public class Customer
{
public void subMenuCustomer()
{
............code............
int subMenuCust;
ServiceLogic addCustomer = new ServiceLogic();
ServiceLogic listAllCustomers = new ServiceLogic();
while(true)
{
System.out.println("Please Choose your preference: ");
System.out.println("Create account, press \"1\": ");
System.out.println("Get list of clustomers, press \"2\": ");
System.out.println("Log out, press \"0\": ";
subMenuCust = input.nextInt();
switch(subMenuCust)
{
case 1 ://Call method createCustomer in class ServiceTech to add new customers
addCustomer.createCustomer(name, lastname, ssNo);
break;
case 3
listAllCustomers.getCustomer();
............more code..............
}
}
When user has added details (social secuity number, name and lastname) it is stored in seperate ArrayList. These three ArrayList are added(merge/concat) together to a fourth ArayList, listCustomer , so that all elements from the three ArrayList end up in same index [101 -54 Clark Kent, 242-42 Linus Thorvalds, ...].
import java.util.ArrayList;
import java.util.Scanner;
public class ServiceLogic
{
//Create new ArrayLists of Strings
private ArrayList<String> listSSNoCustomers = new ArrayList<>();
private ArrayList<String> listNameCustomers = new ArrayList<>();
private ArrayList<String> listLastnameCustomers = new ArrayList<>();
private ArrayList<String> listCustomers;
Scanner input = new Scanner(System.in);
public boolean createCustomer(String name, String lastname, String ssNo) //
{
System.out.println("Write social security number; ");
ssNo = input.next();
//loop to check that it is a uniq social security number
for(String ssNumber : listSSNoCustomers)
{
if (ssNumber.equals(ssNo))
{
System.out.println("This customer already exist. Must be uniq social security number.");
return true;
}
}
//If social security number is not on list, add it
//and continue add first name and surname
listSSNoCustomers.add(ssNo);
System.out.println(ssNo);
System.out.println("Write firstname; ");
name = input.next();
listNameCustomers.add(name);
System.out.println(name);
System.out.println("Write lastnamame; ");
surname = input.next();
listSurnameCustomers.add(lastname);
System.out.println(lastname);
return false;
}
public void setListCustomer(ArrayList<String> listCustomers)
{
this.listCustomers = listCustomers;
}
public ArrayList<String> getCustomer()
{
//ArrayList<String> listCustomers = new ArrayList<>();
for(int i = 0; i <listSSNoCustomers.size(); i++)
{
listCustomers.add(listSSNoCustomers.get(i) + " " + listNameCustomers.get(i) + " " + listFirstnameCustomers.get(i));
}
System.out.println("customer" + listCustomers);
return listCustomers;
}
}
According to the specification we got, when user want to see list of all customer the outputs should be in format [666-66 Bruce Wayne, 242-42 Linus Thorvalds, ...].
When user (staff) choose to enter details in class Customer ( Case 1 ) it works and elements get stored in the Arraylists for social security numbers, name and lastname (have checked that) .
The problem: when I run I can add customers, but when I try to get a list of customer the output: [] . I tried different solution, but same output only empty between the brackets.
So the question, how do I get ouput to work when user choose case 2 to get a list of all cutomers?
currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
I've been teaching myself java and I've stuck on a problem that no matter what I do can't seem to solve. I've done some research but all the options provided don't seem to work. Hopefully you guys might be able to teach me something.
I have a .txt file that contains:
AccountName1:Password1
AccountName2:Password2
AccountName3:Password3
AccountName4:Password4
AccountName5:Password5
The elements of the file are then read and inserted into a List:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public abstract class AccountFileReader {
private static Scanner sc;
public static void main(String[] args) {
try {
// Enables ability to find file in any OS.
String file = File.separator + "some folder name"
+ File.seperator + "AccNamePw.txt";
File f = new File(file);
sc = new Scanner(f);
List<AccountInfo> accounts = new ArrayList<AccountInfo>();
String name = "";
String password = "";
while (sc.hasNext()){
// Reads and checks if there is a new line
String line = sc.nextLine();
// Creates delimiter to make the different elements on file f
String[] details = line.split(":");
// Initializes 1st element
name = details[0];
// Initializes 2nd element
password = details[1];
// Creates new object "a" that has the 2 elements from each line
AccountInfo a = new AccountInfo(name, password);
// Adds the "a" object to the "accounts" List
accounts.add(a);
}
// Iterates list and prints out the list
for(AccountInfo a: accounts){
// The hiccup is in here somewhere. This for loop isn't working in
// a way I think it's supposed to.
// Create new object of the getter, setter class to use in this loop
AccountInfo namPw = new AccountInfo(name, password);
name = namPw.getName();
password = namPw.getPassword();
System.out.println(a.toString() + " " + name
+ " " + password);
}
} catch (FileNotFoundException e) {e.printStackTrace();}
}
}
The getter/setter class is as follows:
public class AccountInfo{
private String name;
private String password;
public AccountInfo(String name, String password) {
this.setName(name);
this.setPassword(password);
}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setPassword(String password) { this.password = password; }
public String getPassword() { return password; }
public String toString(){ return name + " "+ password; }
}
My output is:
AccountName1:Password1 AccountName5:Password5
AccountName2:Password2 AccountName5:Password5
AccountName3:Password3 AccountName5:Password5
AccountName4:Password4 AccountName5:Password5
AccountName5:Password5 AccountName5:Password5
But I want it to return:
AccountName1:Password1 AccountName1:Password1
AccountName2:Password2 AccountName2:Password2
AccountName3:Password3 AccountName3:Password3
AccountName4:Password4 AccountName4:Password4
AccountName5:Password5 AccountName5:Password5
I know that the a.toString() is returning correctly but my namPw.getName() and namPw.getPassword() are only giving me the last element of the List.
What am I not understanding and or missing? How do I get namPw.getName() and namPw.getPassword() to return the List correctly?
The problem is the declaration of nameand password right before the while loop. These variables store the last encountered username and password. When the while loop ends, these variables store the values AccountName5 and Password5 respectively.
When you enter the second for-loop, you first create a new UserAccount with using nameand password which store AccountName5 and Password5.
If you just want to print this list, you do not need to create a copy of the contents of the list. Just do:
for(AccountInfo a : accounts) {
System.out.println(a.toString() + " " + a.getName() + " " + a.getPassword());
}
It's because of this:
for(AccountInfo a: accounts){
**AccountInfo namPw = new AccountInfo(name, password);**
name = namPw.getName();
password = namPw.getPassword();
System.out.println(a.toString() + " " + name
+ " " + password);
You are looping through the AccountInfo objects you already created and then creating a new AccountInfo object and passing in name and password (which get set each time you read in a new line, so the value for them would be the last thing they would be set to when reading the file)
Not sure why you are creating a new AccountInfo object. But in order to get what you want, you'd need to do this:
AccountInfo namPw = new AccountInfo(a.getName(), a.getPassword());
No need to create new object in loop. You are already getting object in a.
Remove object creation line. It is creating object with name and and password which is never going to change as it is outside the loop.
Checkout the following solution:
for(AccountInfo a: accounts){
name = a.getName();
password = a.getPassword();
System.out.println(a.toString() + " " + name + " " + password);
}
I have a List having values which I want to send through mail. But in mail I AM only getting the last value, rather then all values. Below is my code
private String sName[];
private String sID[];
method abc()
{
some code.....
final int numberOfStudentsAdded = recentlyJoinedStudents.size();
sName= new String[numberOfStudentsAdded];
sID=new String[numberOfStudentsAdded]
for(int i=0;i<numberOfStudentsAdded;i++)
{
for(final Student s :recentlyJoinedStudents )
{
sName[i]=s.getName();
sID[i]=s.getId();
}
message.setText(
"<table><tr><td><h6>Student Name</h6></td><td><h6>Student ID</h6></td></tr><tr><td>"
+ sName[i] + "</td><td>" + sID[i] + "</td><td></tr></table>", true);
}}
Problem with above code is suppose I have 3 students in my list. But it gives record of last student. I want required output as
Student Name Student ID
abc 1
xyz 2
pqr 3
but I am getting output as
Student Name Student ID
pqr 3
How can I achieve that. What is wrong in my code.
You are overwritten all the time with the text message property with message.setText(""). And I do not understand the two loops. Try this piece of code instead :)
String text = "<table><tr><td><h6>Student Name</h6></td><td><h6>Student ID</h6></td></tr>";
for(int i=0;i<recentlyJoinedStudents.size();i++) {
text += "<tr><td>" + recentlyJoinedStudents.get(i).getName() + "</td><td>"
+ recentlyJoinedStudents.get(i).getId() + "</td><td></tr>";
}
text += "</table>";
System.out.print(text);
As #a-sir said, you are overriding it everytime by setting value as
Change your code to following
private String sName[];
private String sID[];
method abc()
{
some code.....
final int numberOfStudentsAdded = recentlyJoinedStudents.size();
sName= new String[numberOfStudentsAdded];
sID=new String[numberOfStudentsAdded];
StringBuilder dataTable = new StringBuilder("<table><tr><td><h6>Student Name</h6></td><td><h6>Student ID</h6></td></tr>");
for(int i=0;i<numberOfStudentsAdded;i++)
{
for(final Student s :recentlyJoinedStudents )
{
sName[i]=s.getName();
sID[i]=s.getId();
}
dataTable.append("<tr><td>"+ sName[i] + "</td><td>" + sID[i] + "</td><td></tr>");
}
dataTable.append("</table>");
message.setText(dataTable.toString(), true);
}
I am have trouble creating an array or object(with multiple fields) and sending it to an array-list. Any help would be greatly appreciated. I have spent hours looking through every video on YouTube with the words object and array-list in them and have been unable to find much help.
The program needs to prompt the user to pick a option (1. AddItem) then prompt the user for the name and format (dvd, vhs) and save multiple objects with these variables in an array-list. I either keep having the location where it is saved in memory returned to me or instead of multiple objects one large object is created.
Library:
import java.util.Scanner;
import java.util.ArrayList;
public class Library {
static ArrayList<Object> items = new ArrayList<Object>();
static int menuOption;
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
String title, format;
boolean right = false;
do{
displayMenu();
if (menuOption == 1){
System.out.println("Enter Title: ");
title = scan.next();
System.out.println("Enter format: ");
format = scan.next();
addNewItem(title, format);
} else {System.out.println(items);
}
} while (!right);
}
static int displayMenu(){
System.out.println("Menu: ");
System.out.println("1. Add New Item");
menuOption = scan.nextInt();
return menuOption;
}
static void addNewItem(String title, String format){
MediaItem b = new MediaItem();
b.setTitle(title);
b.setFormat(format);
items.add(b);
}
}
MediaItem:
public class MediaItem {
String title;
String format;
MediaItem(){
title = null;
format = null
}
MediaItem(String title, String format){
title = new String();
format = new String();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
The program will run if you:
1 - Change the line
static ArrayList<Object> items = new ArrayList<Object>();
to
static ArrayList<MediaItem> items = new ArrayList<MediaItem>();
2 - Change the line
System.out.println( items );
to
for ( MediaItem mi : items )
{
System.out.println( mi.getTitle() + ", " + mi.getFormat() );
}
3 - Insert a ";" at the end of the line
format = null
I did it here and it worked.
I either keep having the location where it is saved in memory returned to me
I am guessing you ran into this when you tried to either use System.out.println() to print a MediaItem, or you otherwise tried to automatically convert an object to a string. Whatever approach you took when you were seeing the memory addresses is probably the right way to do it, your problem was only in your displaying of the data.
Consider:
MediaItem item = ...;
System.out.println(item);
By default, Java doesn't know how to convert arbitrary objects to strings when you do stuff like that, and so it just spits out the class name and memory address. You either need to print the fields separately (e.g. Java knows how to display a String already), like:
System.out.println("Title: " + item.getTitle() + " Format: " + item.getFormat());
Or you can override toString() (declared in Object) to provide a custom string conversion:
class MediaItem {
...
#Override public String toString () {
return "Title: " + title + " Format: " + format;
}
}
And then you can print it directly:
System.out.println(item);
It is the default base implementation of Object.toString() that produces those strings with the memory address in them.
Based on your description, I'm guessing you had a roughly working implementation but ran into this issue and ended up changing around (and breaking) a bunch of other unrelated things to try and fix it.