I am struggling with making this code work. Here is my code. First class:
public class PersonalAccount extends Account{
private String cardNumber;
private String cardType;
public ArrayList<PersonalAccount> personalAccounts;
public int personal;
private PersonalAccount(String first, String last, String accountNumber, String cardNumber, String cardType){
super(first, last, accountNumber);
this.cardNumber = "";
this.cardType = "";
}
public void addPersonalAccount(PersonalAccount aPersonalAccount){
personalAccounts.add(aPersonalAccount);
}
public void getNumberOfPersonalAccounts(){
personal = personalAccounts.size();
}
public void listAccounts(){
for (PersonalAccount personalaccount : personalAccounts){
System.out.println("Personal Accounts");
System.out.println(personalaccount);
}
}
public void findAccount(){
int index = 0;
boolean found = false;
while(index < personalAccounts.size() && !found){
PersonalAccount personalaccount = personalAccounts.get(index);
if (personalaccount.getaccountNumber().equals(accountNumber)){
found = true;
}else{
index++;
}
}
}
}
When attempting to create an instance of this class in another class, it instead creates an instance of the PersonalAccount object. Is there a way around this issue? I am very new to Java and BlueJ it should be noted.
EDIT: sorry I should clarify. I'm trying to call the methods from this class in another class. But when declaring
PersonalAccount class1 = new PersonalAccount();
I get the error: constructor PersonalAccount in class PersonalAccount cannot be applied to given types.
I am trying to call the method on a button click (where numAcc is the button):
numAcc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
int personal;
personal = class1.getNumberOfPersonalAccounts();
}
});
You dont have a default constructor so you cannot create a PersonalAccount like this:
PersonalAccount class1 = new PersonalAccount();
You have to pass the parameters first, last, accountNumber, cardNumber, cardType. It should be something like this:
PersonalAccount class1 = new PersonalAccount("FirstName", "Last_Name", "123456", "123456789", "Visa");
Read this: http://www.dummies.com/how-to/content/how-to-use-a-constructor-in-java.html
You don't have a zero-argument constructor for PersonalAccount which is why the given statement would fail.
Is that the problem you are having?
The problem is here that the constructor is private:
private PersonalAccount(String first, String last, String accountNumber, String cardNumber, String cardType)
Two things:
You need to change your constructor such that it is public so that it is accessible:
public PersonalAccount(String first, String last, String accountNumber, String cardNumber, String cardType)
The next thing is to supply parameters such as first, last, accountNumber etc. However, if you declare: public PersonalAccount(), then you would not need to supply arguments when you instantiate the class.
You should now be able to call the methods of this class!
Related
I wrote some classes in Java but when I run the program I receive the error "ArrayIndexOutOfBoundsException", the incriminate class is this:
public class Bank {
private String name;
private int maxbankaccount;
private int activebankaccount;
private String radice = "IT8634";
private Conto[] bankaccount = new Conto[maxbankaccount];
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
}
}
I wrote a tester class to test :
public class TestBank {
public static void main (String[] args) {
Bank b1 = new Bank("Fidelity", 10);
b1.addconto("PROVA");
}
}
Since I didn't seem to have made logical errors using the array I debugged, I realized that in the creation of the array of objects the maxbankaccount variable isn't 10 (value passed in Test) but as default value (0),then I tried passing 10 directly and it works good. Why is not the value 10 of maxbankaccount passed but 0?
private Conto[] bankaccount = new Conto[maxbankaccount];
This initialization takes place before the rest of the constructor runs.
Move it into the constructor:
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
this.bankaccount = new Conto[maxbankaccount];
}
You have indeed made a logical error. The array bankaccount is getting initialized when the class is instantiated and is always 0.
Move it into the constructor and initialize it.
public Bank(String name, int maxbankaccount) {
/* ... */
this.bankaccount = new Conto[maxbankaccount];
}
Further more than the issues that are in the other answers, this
private int activebankaccount;
does not initialize the variable activebankaccount
So in:
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
you are using an uninitialized vale as index of the array bankaccount
I can't figure out the way to save the supplierName value in a class object. I'm trying to change it in an addItem method using user input, and store it in a class object. It doesn't work. What am I doing wrong? Do I need to change my constructor? Or use a getter method?
Here is my code:
import java.util.Scanner;
public class PurchasedItem extends Item {
private String suppplierName;
public PurchasedItem() {}
#Override
public boolean addItem(Scanner input) {
super.addItem(input);
System.out.print("Enter the name of the supplier: ");
suppplierName = input.next();
return true;
}
#Override
public String toString() {
String str = super.toString();
return str + " Supplier: " + suppplierName;
}
}
A solution is to allow the constructor to take an argument such as:
public PurchasedItem(String constructorArgument){
supplierName = constructorArgument;
}
Then, you can do something like: PurchasedItem item = new PurchasedItem("some supplier");.
Since the class variable is private, you will also need getters/setters.
For instance:
Setter:
public void setSupplierName(String s){
this.supplierName = s;
}
Getter:
public String getSupplierName(){
return this.supplierName
}
Then to manipulate, you'd do something like:
item.setSupplierName("some company");
item.getsupplierName();
Though, you should be conscious of thread safety in regards to utilising setters.
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.
I've created a simplified version of my current assignment for my programming course.
I've created a test program that asks the user for an input, studentName, studentName is then validated through another class. My end goal is to print out a method called toString() that holds the value the user has entered for the studentName. Right now my program returns null, not the value of studentName. The problem is I'm not sure how to properly set the values with a constructor.
If you could set up a proper constructor and a way to properly print the value the user has entered through the command prompt, I would appreciate it!
Here is the class that contains the main method. Note: I may have declared too many class objects because I was in a hurry.
import java.util.Scanner;
public class TestMcTest
{
TestMcTest2 test3 = new TestMcTest2();
public static void main(String[] args)
{
TestMcTest test2 = new TestMcTest();
TestMcTest2 test = new TestMcTest2();
test2.getStudentInfo();
System.out.println(test.toString());
}
public void getStudentInfo()
{
int valid = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter a name for a student");
valid = test3.getStudentName(input.nextLine());
}while(valid == 0);
}
}
Here is the class that holds the validation and the toString() method that I want to call into the main method of the class with the main method.
public class TestMcTest2
{
private String studentName;
public String setStudentName()
{
return studentName;
}
public int getStudentName(String studentName)
{
int valid = 0;
if (studentName.length() != 0)
{
valid = 1;
this.studentName = studentName;
}
return valid;
}
public String toString()
{
return this.studentName;
}
}
You dint set the value of variable studentName so the default value of string is printed i.e. null
In TestMcTest you have do
TestMcTest2 test = new TestMcTest2();
test.setStudentName("singhakash");
System.out.println(test.toString());
and in TestMcTest2 change
public void setStudentName(String studentName){
this.studentName = studentName;
}
this will give the expected output.
Btw your method name says opposite of its functionality.
If you could set up a proper constructor and a way to properly print
the value the user has entered through the command prompt, I would
appreciate it!
public class TestMcTest2{
....
public TestMcTest2(String s){
this.studentName = s;
}
}
You have to use the newly constructor now like this:
TestMcTest2 test3 = new TestMcTest2("hot name");
And you can print it out like this after your do-while
System.out.println(test3.toString());
And I'm pretty sure you need the #Override annotation at the toString() method.
EDIT:
#Override <- add this
public String toString()
{
return this.studentName);
}
Ok so this is what I have
public class Register {
public String propertyID;
public String PPSNumber;
Register(String aPropertyID, String aPPSNumber) {
propertyID = aPropertyID;
PPSNumber = aPPSNumber;
}
public void setPPSNumber(String aPPSNumber) {
PPSNumber = aPPSNumber;
}
public String getPPSNumber() {
return PPSNumber;
}
public String getPropertyID() {
return propertyID;
}
}
Then I have this
public static ArrayList<Register> registers = new ArrayList<Register>();
public static void main(String[] args) {
String userInput1 = "", userInput2 = "", userInput3 = "";
userInput1 = JOptionPane.showInputDialog("Enter your PPSNumber");
userInput2 = JOptionPane.showInputDialog("Enter your propID");
registers.add("number", "id");
}
I don't understand why It wont let me add to the ArrayList. Is there some way of adding class types to ArrayLists?
Try this instead :
registers.add(new Register("number","id"));
EDIT 1:
To answer your question, you can create a separate "register" and the use the getters :
Register aRegister = new Register("number","id");
registers.add(aRegister);
System.out.println(aRegister.getPropertyID()+" "+ aRegister.getPPSNumber());
Your List is of type Register so you need to add object of Register class only.
Nothing wrong in create as many Register objects as required.
You can implement toString() method inside Register class then the below sysout will work given the register variable is initialized with Register object. Check this How to override toString() properly in Java? to know about toString implementation.
System.out.println(register)