I'm trying to auto generate an id for customers,
and all i get is 0 every time.
Pretty sure the problem is in public void regCustomer().
public class User {
private String firstName, gender, age;
String surename;
private int customerID;
private static int idCounter = 1000;
User next;
public User(String fN, String sn, String g, String a) {
firstName = fN;
surename = sn;
gender = g;
age = a;
//customerID = cID;
next = null;
}
public void setCustomerID() {
customerID = idCounter++;
}
public int getCustomerID() {
return customerID;
}
public String toString() {
return customerID + "\t" + surename + "\t" + firstName + "\t" + age
+ "\t" + gender;
}
}
In the Window class
public void regCustomer() {
//int customerID = 0;//= Integer.parseInt(customerIDField.getText());
String firstName = firstNameField.getText();
String surename = surenameField.getText();
String gender = genderField.getText();
String age = ageField.getText();
if (!firstName.equals("") && !surename.equals("") && !gender.equals("")&& !age.equals("")) {
userA.regCustomer(new User(firstName, surename, gender,age));
User u = new User(firstName, surename, gender,age);
u.getCustomerID();
customerIDField.setText("");
firstNameField.setText("");
surenameField.setText("");
ageField.setText("");
genderField.setText("");
firstNameField.requestFocus();
} else
JOptionPane.showMessageDialog(this, "Alle felt må fylles inn");
}
You never set the ID and that is why it is zero.
You can use a private static final AtomicInteger to generate your id sequence; simply read from it in your constructor:
private static AtomicInteger ID_GENERATOR = new AtomicInteger(1000);
public User(String fN, String sn, String g, String a) {
customerID = ID_GENERATOR.getAndIncrement();
//rest of constructor
}
You should use an AtmoicInteger as this is thread safe and the getAndIncrement method is atomic. There are not such guarantees for an int.
The question that needs to answered is whether these items are persisted in any way, and if so what happens then - id generation will always start from 1000 using this technique.
Move customerID = idCounter++; to the constructor.
Related
I am looking to create a leisure centre booking system in Java, which utilises OOP.
2 of the classes collect names and addresses and membership type, which are added to an ArrayList called memberRegister. How can I print all of the member details (i.e. what is stored in the array list), thus outputting Name, Address, Membertype, etc, all in one command?
My source code for classes in question follows...
public class Name {
private String firstName;
private String middleName;
private String lastName;
//constructor to create object with a first and last name
public Name(String fName, String lName) {
firstName = fName;
middleName = "";
lastName = lName;
}
//constructor to create object with first, middle and last name
//if there isn't a middle name, that parameter could be an empty String
public Name(String fName, String mName, String lName) {
firstName = fName;
middleName = mName;
lastName = lName;
}
// constructor to create name from full name
// in the format first name then space then last name
// or first name then space then middle name then space then last name
public Name (String fullName) {
int spacePos1 = fullName.indexOf(' ');
firstName = fullName.substring(0, spacePos1);
int spacePos2 = fullName.lastIndexOf(' ');
if (spacePos1 == spacePos2)
middleName = "";
else
middleName = fullName.substring(spacePos1+1, spacePos2);
lastName = fullName.substring(spacePos2 + 1);
}
// returns the first name
public String getFirstName() {return firstName; }
// returns the last name
public String getLastName() {return lastName; }
//change the last name to the value provided in the parameter
public void setLastName(String ln) {
lastName = ln;
}
//returns the first name then a space then the last name
public String getFirstAndLastName() {
return firstName + " " + lastName;
}
// returns the last name followed by a comma and a space
// then the first name
public String getLastCommaFirst() {
return lastName + ", "+ firstName;
}
public String getFullname() {
return firstName + " " + middleName + " " + lastName;
}
}
public class Address {
private String first_line, town, postcode;
public Address(String first_line, String town, String pcode)
{
this.first_line = first_line;
this.town = town;
postcode = pcode;
}
public Address()
{
first_line = "";
town = "";
postcode = "";
}
public String getFirst_line() {
return first_line;
}
public void setFirst_line(String first_line) {
this.first_line = first_line;
}
public String getTown() {
return town;
}
public void setTown() {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
public class Member extends Person {
private String id; // membership ID number
private String type; // full, family, exercise, swim, casual
public Member(String id, String type, Name n, Address a)
{
super(n, a);
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
import java.util.ArrayList;
public class Registration {
private ArrayList<Member> memberRegister;
public Registration()
{
memberRegister = new ArrayList();
}
public void register(Member m)
{
memberRegister.add(m);
}
public int countMembers()
{
return memberRegister.size();
}
public Member getMember(int i) {
return memberRegister.get(i);
}
public class Main {
public static void main(String[] args) {
Name n = new Name("Kieran", "David", "Nock");
Address a = new Address ("123 Skywalker Way", "London", "NW1 1AA");
Member m = new Member("001", "Full", n, a);
Registration reg = new Registration();
reg.register(m);
System.out.println(reg.countMembers());
System.out.println(reg.getMember(0).getName().getFullname());
}
}
Hey I would do it in following way
First override toString() methods of all the model classes and remember to override Member class toString() in following way
#Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}'+super.toString();
}
After this adding the below single line in main method would work
reg.getMemberRegister().stream().forEach(System.out::println);
NOTE: create a getter for memberRegister list which is present in Registration Class
How my program is set up is that my code runs and allows the user to create a new movie object which is then stored to the constructor. It then gives the option to create a new movie which is then stored in the same movie object, which ultimately overwrites the previous movie object that was created. Many implementation go about putting the object creation in a loop, but this asks for all the multiple values to be stored into multiple objects all at once, I'm not looking to do that. I'm not sure how to go about solving this.
Here's my code
Movie class
public class Movie {
private int id;
private String name;
private String description;
private String[] genre;
private String[] actors;
private String[] language;
private String countryOfOrigin;
private Map<String, Integer> ratings;
Movie() {
}
//Constructor
public Movie(int id, String name, String description, String[] genre, String[] actors, String[] language, String countryOfOrigin, Map<String, Integer> ratings) {
this.id = id;
this.name = name;
this.description = description;
this.genre = genre;
this.actors = actors;
this.language = language;
this.countryOfOrigin = countryOfOrigin;
this.ratings = ratings;
}
//setters
public void setid(int id) {
this.id = id;
}
public void setname(String name) {
this.name = name;
}
//getters
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "\nMovie Id: " + id + " \nMovie Name: " + name + "\nMovie Description: " + description + "\nMovie Genre(s): " + Arrays.toString(genre) + "\nMovie Actor(s): " + Arrays.toString(actors) + "\nMovie Language(s): " + Arrays.toString(language) + "\nCountry of Origin: " + countryOfOrigin + "\nRatings: " + ratings +"";
}
}
Main class
public class Main {
// --- Private global scanner initialization --- //
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws Exception {
while (loopAgain) {
Random rand = new Random();
int id = rand.nextInt(MAX);
System.out.println("\nCreate Poll");
System.out.println("\nEnter the Movie Name: ");
String name = input.nextLine();
Movie movie1 = new Movie(id, name, description, genre, actors, language, countryOfOrigin, mapRatings);
System.out.println("Create new movie? (y/n): ");
String answer = input.nextLine();
if (answer.equals("y") || answer.equals("Y")) {
loopAgain = true;
}
}
}
}
You can store the movie objects in some kind of container after you create them. So you can use an ArrayList for example
ArrayList<Movie> movies= new ArrayList<Movie>();.
You can put this above your while loop. Then after you create the object you can add it into the container such as movies.add(movie1) you can put this right under where you called the constructor. Later on to access the object, you can use movies.get(index)
So I have a while loop which stores all of my variables, but my problem is that whenever the program loops it changes the values of the object in the previous array. So employeeArray is filled with all objects of the same values rather than storing the previous value and creating a new one. I am reading text from a .csv file. Can somebody please explain to me how to store my Employee objects without them changing each loop? Let me know if you need any clarification I know I probably missed some information somebody trying to help me may need. Anyways my code is below, I have 3 different classes but Im just going to put the Employee and EmpQuery class on here. I believe the problem is with my variables in the Employee class. PLEASE HELP ME, it would be greatly appreciated.
public class EmpQuery extends Employee {
public static void fillArrayObjects(Scanner s, Employee[] e){
//VARIABLES
String sNextLine;
int counter = 0;
int parsedString;
String employeeID;
String employeeName;
String employeeDepartment;
String employeeStartDate;
int employeeEarnings;
//DECLARE ARRAY TO HOLD EMPLOYEE OBJECTS
Employee employeeArray[] = new Employee [50];//50 records I believe
while(s.hasNext()){
//SCANNER AND SEPARATE STRING VALUE IN LINE
sNextLine = s.nextLine();
String[] tempSplit = sNextLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)", -1);
//REMOVE EVERYTHING EXPCEPT NUMBERS [4]
tempSplit[4] = tempSplit[4].replace(",","");
tempSplit[4] = tempSplit[4].replace("$","");
tempSplit[4] = tempSplit[4].replace("\"", "");
tempSplit[4] = tempSplit[4].replace(".00","");
parsedString = Integer.parseInt(tempSplit[4]);
//STORE TEMP SPLITS IN NEW VARIABLES
employeeID = tempSplit[0];
employeeName = tempSplit[1];
employeeDepartment = tempSplit[2];
employeeStartDate = tempSplit[3];
employeeEarnings = parsedString;
//CALLING FROM EMPLOYEE CLASS
Employee.enterData(employeeID, employeeName, employeeDepartment, employeeStartDate, employeeEarnings);
//STORE EACH NEW EMPLOYEE IN employeeArray
Employee i = new Employee(employeeID, employeeName, employeeDepartment, employeeStartDate, employeeEarnings);
employeeArray[counter] = i;
//TESTS
System.out.println(counter + " " + Employee.getEarnings(employeeArray[0]));//employee[1] keep changing every loop
//INCREMENT COUNTER
counter++;
}
System.out.println(Employee.getEarnings(employeeArray[12]));
System.out.println(Employee.getID(employeeArray[3]));
}
*************************************NEW CLASS******************************
package employeedb;
/**
*
* #author Daniel
*/
public class Employee {
//VARIABLES***************************************************************************************************
public String empID;
public String empName;
public String department;
public String startDate;
public int earnings;
Employee newGuys;
//EMPLOYEE*********************************************************************************************************
public Employee(){
empID = "";
empName = "";
department = "";
startDate = "";
earnings = 0;
}
public Employee(String iD, String name, String employeeDepartment, String startingDate, int salary){
empID = iD;
empName = name;
department = employeeDepartment;
startDate = startingDate;
earnings = salary;
}
public Employee(String iD, String name){
empID = iD;
empName = name;
}
//ENTER DATA*******************************************************************************************************
public void enterData(){
empID = "";
empName = "";
department = "";
startDate = "";
earnings = 0;
}
//ENTER DATA
public void enterData(String iD, String name){
empID = iD;
empName = name;
department = "";
startDate = "";
earnings = 0;
}
//ENTER DATA
public void enterData(String iD, String name, String employeeDepartment, String startingDate, int salary){
empID = iD;
empName = name;
department = employeeDepartment;
startDate = startingDate;
earnings = salary;
}
//VIEW SPECIFIC FIELD****************************************************************************************************
public void viewEmployeeID(Employee variable){
System.out.println(empID);
}
public void viewEmployeeName(Employee variable){
System.out.println(empName);
}
public void viewDepartment(Employee variable){
System.out.println(department);
}
public void viewStartDate(Employee variable){
System.out.println(startDate);
}
public void viewEarnings(Employee variable){
System.out.println(earnings);
}
//VIEW DATA**********************************************************************************************************
public void viewAllData(){
empID = "";
empName = "";
department = "";
startDate = "";
earnings = 0;
System.out.println("Employee ID: " + empID);
System.out.println("Employee name: " + empName);
System.out.println("Employee department: " + department);
System.out.println("Employee start date: " + startDate);
System.out.println("Employee earnings: $" + earnings);
System.out.println("");
}
//VIEW DATA
public void viewData(String iD, String name, String employeeDepartment, String startingDate, int salary){
empID = iD;
empName = name;
department = employeeDepartment;
startDate = startingDate;
earnings = salary;
System.out.println("Employee ID: " + empID);
System.out.println("Employee name: " + empName);
System.out.println("Employee department: " + department);
System.out.println("Employee start date: " + startDate);
System.out.println("Employee earnings: $" + earnings);
System.out.println("");
}
//RETURN DATA*********************************************************************************************************
//GET ID
public String getID(Employee variable){//void
return empID;
}
//GET NAME
public String getName(Employee variable){
return empName;
}
//GET DEPARTMENT
public String getDepartment(Employee variable){
return department;
}
//GET START DATE
public String getStartDate(Employee Variable){
return startDate;
}
//GET EARNINGS
public int getEarnings(Employee Variable){
return earnings;
}
}
The main problem is that you set the variables in Employee as static, that means they are shared in every instance of the class.
They should not be static so every object has their own.
I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.
In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();
I don't see what I'm doing wrong here or how anything here is static without it being declared that way. I just need to be pointed in the right direction here.
Test code:
public class PaintballPlayerTest
{
//Test program for PaintballPlayer assignment
public static void main (String [] args)
{
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer ("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer ("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer ("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
My code:
import java.util.*;
public class PaintballPlayer
{
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private int count;
private static int totalPlayers;
private int playerID;
private int players;
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
id = totalPlayers++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
}
public PaintballPlayer()
{
totalPlayers++;
}
public static int getTotalPlayers()
{
return totalPlayers;
}
public String toString()
{
String name;
String n;
name = firstName + " " + middleName + " " + lastName;
return name;
}
public int getPlayerID()
{
playerID = count;
return playerID;
}
}
Again, my problem is with the getTotalPlayers() method.
EDIT: This is my edited code applying the fixes provided. Thank you!
getTotalPlayers() is not a static method, so you need an instance of PaintballPlayer to call this method.
If you want to store the total players inside PaintballPlayer, you need an static attribute (same reference for all instances):
class PaintballPlayer {
private static int totalPlayers;
public PaintballPlayer() {
totalPlayers++;
}
public static int getTotalPlayers() {
return totalPlayers;
}
}
On your code there are a few problems, on the constructor #1
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
players = 0;
id = count++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
The variables players and count are being reseted while the variable count is increased two times.
And in the constructor #2 the problem is worst:
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
players = count++;
}
because you are increasing the value of count two times besides the 2 times in the original constructor, so four times in total.
Once u have done what Devon Freese says u will have to modify the constructor of PaintballPlayer
public PaintballPlayer(String first, String middle, String last)
{
id = totalPlayers++;
firstName = first;
middleName = middle;
lastName = last;
}
Try this.
import java.util.*;
public class PaintballPlayer {
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private static int count;
private static int totalPlayers;
private int playerID;
private static int players;
public PaintballPlayer(String first, String middle, String last) {
count++;
id = count;
players = count;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l) {
this(f, "", l);
id = count;
players = count;
}
public String toString() {
String name = firstName + " " + middleName + " " + lastName;
return name;
}
public static int getTotalPlayers() {
totalPlayers = players;
return totalPlayers;
}
public int getPlayerID() {
playerID = count;
return playerID;
}
}
class PaintballPlayerTest {
//Test program for PaintballPlayer assignment
public static void main(String[] args) {
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
}
}