Hello i can not write the JTextField's value to the ArrayList in another class the error is "...String can not be converted to Object" how can i fix it?
here is the arraylist class
public class MemberList
{
private ArrayList < Member> members;
/**
* Create a Member.
*/
public MemberList()
{
members = new ArrayList < Member>();
}
/**
* Add a member to this member list.
* #param member the member to be added
*/
public void addMember(Member member)
{
members.add(member);
}
}
and the GUI
public class Test extends JFrame implements ActionListener {
private JTextField jtFName, jtLName, jtMemberNo;
private int nextMemNo;
private MemberList members;
private JFrame frame;
#Override
public void actionPerformed(ActionEvent evt) {
members = new MemberList();
if (evt.getActionCommand().equals("Add Member")) {
if (jtLName.getText().equals("") && (jtFName.getText().equals(""))) {
jtMember.setText("No names");
} else if (jtFName.getText().equals("")) {
jtMember.setText("No first name");
} else if (jtLName.getText().equals("")) {
jtMember.setText("No last name");
} else if (!jtLName.getText().equals("") && (!jtFName.getText().equals(""))) {
btnOne.setText("Confirm");
String fName = jtFName.getText();
String memNo = "1";
String lName = jtLName.getText();
members.addMember(member);
}
} else if (evt.getActionCommand().equals("No. of Members")) {
btnTwo.setText("Clear Number");
jlbMember.setVisible(true);
} else if (evt.getActionCommand().equals("Clear Number")) {
jtFName.setText("");
jtLName.setText("");
} else if (evt.getActionCommand().equals("Quit")) {
System.exit(0);
}
}
}
What do i need to do to add jtFName in the ArrayList?
Sorry for the bad editing and thanks
You have to create a new instance of your Member class and pass it to your addMember method. For example
Member member = new Member(fName, lName); //replace with your actual constructor logic
members.addMember(member);
Your List members contains object of type Member not of type String
Either you make that your List contains String like:
members = new ArrayList<String>();
Or you make a constructor for your Member class in which you pas the String to the object and add the new Object to the List like:
public class Member{
private String name;
public Member(String name){ //create constructor with String argument
this.name = name;
}
}
members.addMember(new Member(name)) //add new Member to list
I can't see your Member class but when I look at your code I think it has a fName, lName and memNo. So in your program the constructor will look like:
public class Member{
private String fName;
private String lName;
private String memNo;
public Member(String fNamen, String lName, String memNo){ //create constructor with String arguments
this.fName= fName;
this.lName= lName;
this.memNo= memNo;
}
}
And add it to the List like:
members.addMember(new Member(fName, lName, memNo));
Related
I have 2 different classes, Employee, PersonnelManager. I am trying to declare and instantiate an array of Employee in PersonnelManager. without using inheritance, just two completely seperate classes
public abstract class Employee {
private String firstName;
private String lastName;
private double wage;
public Employee() {
firstName = "";
lastName = "";
wage = 0.0;
}
}
public class PersonnelManager {
public Employee [] EmployeesArray;
public PersonnelManager() {
EmployeesArray= {Employee.this()}; // this is not working
}
in the Constructor of PersonnelManager How can I instantiate the array. Thank you.
You can initialize the array like below -
public PersonnelManager() {
EmployeesArray= new EmployeesArray[5];
}
or you can pass the size in constructor to make it dynamic-
public PersonnelManager(int size) {
EmployeesArray= new EmployeesArray[size];
}
Hope this will help you.
public abstract class Employee {
private String firstName;
private String lastName;
private double wage;
public Employee() {
firstName = "";
lastName = "";
wage = 0.0;
}
}
public class PersonnelManager {
public Employee [] EmployeesArray;
public PersonnelManager() {
EmployeesArray= new Employee[10]; // 10 is the size of an array
}
I think you're trying to instantiate an empty array of Employees in your PersonnelManager, but you're using the wrong syntax. You can do that with this:
EmployeesArray = new EmployeesArray[size];
Note that you'll have to supply a size. If you want more flexibility, then you might want to use a List instead of an array:
public class PersonnelManager {
public List<Employee> employees;
public PersonnelManager() {
employees = new ArrayList<>();
}
}
I have 2 subclasses(MultiCard and BasicCard) and I want to call a method(addCurrency) belonging to MultiCard from the class Bank. The method is used to add more currency inside a MultiCard which has an ArrayList of currencies. However, because MultiCard is the sub-class of class Card, I can't access the MultiCard. All cards are stored in a List<Card>cards;
I do not want to use a casting based solution (checking with instanceof and then casting the Card instance to a MultiCard)
The Super Class:
public abstract class Card implements Comparable<Card>, Cloneable
{
protected String id;
protected String name;
protected List<Purchase> purchases;
static int counter = 1000;
public Card(String name)
{
counter++;
this.id = Integer.toString(counter);
this.name = name;
this.purchases = new ArrayList<Purchase>();
}
The method I want to use in class MultiCard extends Card
public class MultiCard extends Card implements Cloneable
{
protected static List<String> currencies;
protected double[] balance;
public static final int currencyCount = 5;
public MultiCard (String name)
{
super (name);
currencies = new ArrayList<String>();
balance = new double[currencyCount];
currencies.add ("AUD");
for (int i = 0; i < balance.length; i++)
balance[i] = 0;
}
public boolean addCurrency (String currency)
{
if (currencies.size () == currencyCount ||containsCurrency (currency)) {
return false;
}
currencies.add (currency);
return true;
}
The method addCurrency() that I need to modify in class Bank
private static final String[] currencyLabel = { "AUD", "NZD", "USD", "CND", "YEN", "BPD" };
private static final double[] currencyRate = { 1.0, 1.2, 0.75, 0.85, 80, 0.7 };
private String adminUsername;
private String adminPassword;
Map<String, User> users = new HashMap<>();// username
public Bank(String admName, String admPassword){
this.adminUsername = admName;
this.adminPassword = admPassword;
public boolean addCurrency(String cardID, String username, String password, String currency) { ...
}
The method addCurrency is used to add a currency inside a List which is in MultiCard. It calls the method in the MultiCard
This is what I tried:
public boolean addCurrency(String cardID, String username, String password, String currency)
{
User user = users.get(username);
user.getACard(cardID, username, password); // here is my problem - a Card instance is returned, which must be cast to a MultiCard
}
Since the question is a bit confusing, I assume that when you are calling user.getACard(cardID, username, password) method, you are getting an object of Card . Ideal fix would be that To invoke addCurency() method,
You can add an abstract method public boolean addCurrency (String currency) in the Card class (if at all you are allowed to modify the Card class).
Otherwise you will have to cast the Card Object to MultiCard Object.
So I am trying to pass an ArrayList to my main method, but eclipse is telling me I need to change my arraylist to a static. I know I'm doing something wrong but I can't figure it out.
ArrayList<Patient> pList = Doctor.getPatientList();
this is the call I have in my main method.
public class Doctor {
public ArrayList<Patient> patientList = new ArrayList<Patient>();
}
public void loadPatientData() {
BufferedReader read2 = null;
try {
read2 = new BufferedReader(new FileReader("data/patient_list.txt"));
String line;
while ((line = read2.readLine()) != null) {
line = read2.readLine();
if (line == null) {
break;
}
String[] lineValues = line.split(","); //split the string on this value into array
String firstName = lineValues[0];
String lastName = lineValues[1];
String address = lineValues[2];
String city = lineValues[3];
String state = lineValues[4];
String zip = lineValues[5];
String ssn = lineValues[6];
String genderNeedsConvert = lineValues[7];
String weightNeedsDouble = lineValues[8];
String heightNeedsDouble = lineValues[9];
String symptomsNotReady = lineValues[10]; // these need to be broken up further (using semicolons)
char gender = genderNeedsConvert.charAt(0);
double weight = Double.parseDouble(weightNeedsDouble);
double height = Double.parseDouble(heightNeedsDouble);
Patient patient = new Patient(firstName, lastName, address, city, state, zip, ssn, gender, weight, height, symptomsNotReady);
patientList.add(patient); // must be of patient type.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read2 != null) {
try {
read2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<Patient> getPatientList() {
return patientList;
}
This is a shortened version of my Doctor class.
public class Patient {
private String patientID;
private String firstName;
private String lastName;
private String ssn;
private char gender;
private String address;
private String city;
private String state;
private String symptoms;
private String zip;
public ArrayList<Diagnosis> diagnoses = new ArrayList<Diagnosis>();
//private Diagnosis diagnoses = new Diagnosis(0, null);// new diagnoses called as Diagnoses datatype
public ArrayList<Medication> newMedication = new ArrayList<Medication>();
//private Medication newMedication = new Medication(0, null);// newMedication called as medication datatype
ArrayList<String> symptom = new ArrayList<String>();
ArrayList<String> symptomCompare = new ArrayList<String>();
private double weight;
private double height;
int k = 0;
public Patient(String firstName,String lastName,String address,String city, String state,String zip,String ssn,char gender,double weight,double height,String symptoms){
this.firstName = firstName;
this.lastName = lastName;
this.ssn = ssn;
this.gender = gender;
this.weight = weight;
this.height = height;
this.address = address;
this.city = city;
this.state = state;
this.symptoms = symptoms;
this.zip = zip;
this.patientID = ssn.replace("-", ""); // removes dashes from ssn and sets the value to patientID
this.patientID = this.patientID.replace(" ", ""); //removes spaces from patientID
this.patientID = this.patientID + this.firstName.substring(0, 1) + this.lastName.substring(0, 1);
}
and above is the shortened patient class. I've been sitting here for a few hours trying different things but it keeps telling me to change the getPatientList() method to static. What am I doing wrong?
Doctor.getPatientList() is the syntax for calling a static method, since Doctor is a class name.
If you want to call an instance method (and getPatientList() is currently an instance method), you should call it using an instance of a Doctor:
Doctor doctor = new Doctor();
ArrayList<Patient> pList = doctor.getPatientList();
What ever variables/method you declare as static as known as class members. Strictly speaking, they belongs to the class instead of being an object's attribute.
When a variable is static, it exist even before the object is created. So what does that means?
Static methods can access static variables/methods.
Static methods cannot access non-static variables/methods. (because they don't exist)
If you want to let static methods access non-static variables/methods. One of the ways is to instantiate(create) the object which the method/variable you wanted to access belong to that object first.
The reason you need to instantiate first before you can access it is because you want to make them exist first. Class itself is only a blueprint, you need to create an object (to make them exist) before you can interact with it.
Example:
Doctor doctor = new Doctor();
ArrayList<Patient> list = doctor.patientList;
//Only possible if patientList is not private
If patientList is private in Class Doctor, you need to use a getter:
Doctor doctor = new Doctor();
ArrayList<Patient> list = doctor.getPatientList();
//getPateientList is a method in Doctor class
Use static modifier with public ArrayList<Patient> getPatientList():
public static ArrayList getPatientList()
You are invoking this method on class Doctor, and thus this method must be declared static.
You have to declare the class object first then call its function. Like:
Doctor doc = new Doctor();
doc.getPatientList();
Else you will have to make the function static.
In the Doctor class, the patientList, loadPatientData() and getPatientList() members are all "instance" members of the class Doctor, which means you need an instance or an object of the type Doctor.
So, to call getPatientList(), you need to create a Doctor object as below:
Doctor doc = new Doctor();
doc.getPatientList();
static members are accessed using the name of the class where as instance members are accessed using the name of the object.
I've got an abstract class called customer and another classe called payCust that extends this abstract class. There is another client class that initializes a list of customers.List<Customer> custList = new ArrayList<>();
the customer class has a constructor as follows:
public Customer(String name, String email, String mag) {
this.CusEmail = email;
this.CusName = name;
this.magazine = mag;
}
payCust has the following constructor:
public PayCust(String _name, String _email, String _accountType, String _custMag) {
super(_name, _email, _custMag);
this.accountType = _accountType;
}
all the variables have public get and set methods. e.g.
public void setName(String name) {
this.CusName = name;
}
public String getName() {
return this.CusName;
}
my question is that if the custList had a PayCust added to it. how can i edit the accountType of a customer from that list?
note: email is unique to every customer
You will have to check the instance type of the object within the ArrayList and cast it for usage.
Something like this, for example:
for (Customer c : custList){
if(c instanceof PayCust){
PayCust pc = (PayCust) c;
pc.getAccountType();
}
}
You would have to cast it to a PayCust (assuming you know for a fact that it's a PayCust):
PayCust example = (PayCust) custList.get(0);
String accountType = example.getAccountType ();
...
This is basically a Java code converter. It involves a GUI let user input class type, name and method. To store the values, I've created a class VirtualClass with an ArrayList<VirtualClass> classes to store variables boolean isPrivate, String className and String methodName. However, I found that nothing was stored into the ArrayList...please help me to see what's the problem
Below is the class VirtualClass
import java.util.*;
public class VirtualClass {
private static ArrayList<VirtualClass> classes = new ArrayList<VirtualClass>();
private boolean isPrivate;
private String className;
private String methodName;
public void setVirtualClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
}
public void createClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
classes.add(this);
}
For reference, here's some relevant code from the GUI which let users create class
public class GuiAddClass extends JFrame{
private VirtualClass stObject;
...
private class Handler implements ActionListener{
public void actionPerformed(ActionEvent event){
String cName = inputClassName.getText();
String mName = inputMethodName.getText();
boolean isP = true;
if (classObject.checkName(cName) == false){
JOptionPane.showMessageDialog(null, "Class name invalid. " +
"\nEntered name should not contain java keywords or equal to other existing names. " +
"\nPlease try again.");
} else if (classObject.checkName(cName) == true) {
JOptionPane.showMessageDialog(null, "Class saved.");
// this message pane has popped up
cName = inputClassName.getText();
mName = inputMethodName.getText();
if (event.getSource() == publicButton) {
isP = false;
} else if (event.getSource() == privateButton) {
isP = true;
}
stObject = new VirtualClass();
stObject.createClass(cName, mName, isP);
}
}// end actionPerformed()
}// end Handler class
And here's a couple of methods from another class for display the final javaCode
public String getClassName(){
String cName = "classname";
String c = "c";
for (int i=0; i<classes.size(); i++){
c = classes.get(i).className;
}
cName = c;
return cName;
}
public String getMethodName(){
String mName = "methodname";
String m = "m";
for (int i=0; i<classes.size(); i++){
m = classes.get(i).methodName;
}
mName = m;
return mName;
}
public boolean getIsPrivate(){
boolean isP = false;
for (int i=0; i<classes.size(); i++){
isP = classes.get(i).isPrivate;
}
return isP;
}
Here's the method to generate the Java code
public String getJavaCode(){
String javaCode = (classObject.getPublic() + " class " +
stObject.getClassName() + stObject.getListSize() +
"{\n"+"\t"+"public void "+stObject.getMethodName()+"{\n"+"\t}"+"\n}");
return javaCode;
And what would display in my programme is like this, where c should be class name, m should be method name, and 0 = classes.size()
public class c0{
public void m{
}
}
Can anyone help me to spot out the problem please?
I just have no idea and the answers I received doesn't seem to work. Please help!
From information you posted, seems strange that you initiate VirtualClass stObject into actionPerformed method. Its mean that each time you recreate your object.
Make your VirtualClass stObject to be global for example, like:
private VirtualClass stObject;
...
stObject = new VirtualClass();
private class Handler implements ActionListener{
public void actionPerformed(ActionEvent event){
...
stObject.createClass(cName, mName, isP);
You have a couple of problems with your code. But mainly, you creational logic does not make much sense. You should not add an instance into your Static collection using a method of the instance. My advice would be to use a static factory method to do this. Something like this instead :
public class VirtualClass {
private static List<VirtualClass> classes = new ArrayList<VirtualClass>();
private boolean isPrivate;
private String className;
private String methodName;
//A private constructor
private VirtualClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
}
private void setClassName(String className){
this.className = className;
}
private void getClassName(){
return className;
}
public static VirtualClass createClass(String name, String method, boolean isP){
VirtualClass virtualClass = new VirtualClass(String name, String method, boolean isP);
classes.add(virtualClass);
return virtualClass;
}
}
The way your code is done now, the problems can be in a lot of places in your client classes. This structure is safer and generally used.
Also you should not type your collection with ArrayList but use the implemented interface instead, List. how to use an array list?