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.
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
The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.
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);
}
I have the following code:
public static void main(String[] args) {
Player players[] = new Player[2];
Scanner kb = new Scanner(System.in);
System.out.println("Enter Player 1's name");
players[0] = new Player(kb.nextLine());
System.out.println("Enter Player 2's name");
players[1] = new Player(kb.nextLine());
System.out.println("Welcome "+ players[0].getName() + " and " + players[1].getName());
}
It is meant to create a new player object and store the name of the player, while keeping all the objects in the array.
Here is the player class:
public class Player {
static String name;
public Player(String playerName) {
name = playerName;
}
public String getName(){
return name;
}
}
What actually happens is that it works when I just have 1 object, but when I have 2, each element in the array is the same as the second. When I have 3 objects in the array, each element is the same as the 3rd, etc.
I'm not sure why this is happening, or how to correct it, and it's been baffling me for hours :/
Its because of the static field. Statics are used across object instances. They are stored at class level.
Below code would work:
class Player
{
String name;
public Player(String playerName)
{
name = playerName;
}
public String getName()
{
return name;
}
}
Change static string name to private string name
Name field should not be static. Static means that the variable is actually global and shared across all class instances.
With the keyword static you have made name a class variable which is NOT an instance variable. A class variable is common to all the objects. Click for some more reading.
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!