Calling Set / Get Methods from another Class and .java file - java

Alright, I'm trying to call setters and getters from another function that's inside another class, in another file. Here's what I'm getting, and I really don't know what I'm doing wrong...
Bank.java
package Bank;
import java.io.*;
import java.util.*;
public class Bank
{
public static void main (String args[]) throws FileNotFoundException
{
final String fileName = "Bank/AcctInfo.txt";
File accounts = new File(fileName);
ArrayList <Object> acctInfo = new ArrayList <Object> ();
acctInfo = setObjects(accounts);
}
public static ArrayList setObjects(File document) throws FileNotFoundException
{
ArrayList <Object> objectArray = new ArrayList <Object> ();
Scanner fileInput = new Scanner(document);
String blankInfo;
String accountType;
String customerType;
String customerName;
int accountNumber;
float balance;
int counter = 0;
while (fileInput.hasNext())
{
accountNumber = fileInput.nextInt();
blankInfo = fileInput.nextLine();
accountType = fileInput.nextLine();
customerName = fileInput.nextLine();
customerType = fileInput.nextLine();
balance = fileInput.nextFloat();
blankInfo = fileInput.nextLine();
objectArray.add(new BankAccount());
objectArray.get(counter).setAccNumber(accountNumber);
counter++;
}
return objectArray;
}
}
BankAccount.java
package Bank;
public class BankAccount extends Bank
{
private int accNumber;
private String accType;
private String cusName;
private String cusType;
private float bal;
public void setAccNumber(int accountNumber)
{
int accNumber = accountNumber;
}
public int getAccNumber()
{
return accNumber;
}
public void setAccType(String accountType)
{
String accType = accountType;
}
public String getAccType()
{
return accType;
}
public void setCusName(String customerName)
{
String cusName = customerName;
}
public String getCusName()
{
return cusName;
}
public void setCusType(String customerType)
{
String cusType = customerType;
}
public String getCusType()
{
return cusType;
}
public void setBal(float balance)
{
float bal = balance;
}
public float getBal()
{
return bal;
}
}
Errors:
Bank.java:51: error: cannot find symbol
objectArray.get(counter).setAccNumber(accountNumber);
^
symbol: method setAccNumber(int)
location: class Object
Note: .\Bank\Bank.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
It's not completed yet, but if someone can help me through that bit, it'd be a huge help...

Instead of ArrayList<Object>, use ArrayList<BankAccount>.
Object is a class that doesn't have a method with the signature setAccNumber(int) whereas BankAccount does.
The ArrayList<Object> declaration says that you're declaring an ArrayList that will have Objects inside it; since all classes inherit from Object, putting instances of BankAccount in the list is valid, but as far as the compiler is concerned, when you refer to an element inside the list, it's an Object and only has the standard methods available to Object.
There are other peculiarities in your class too (e.g. in your setter methods, you declare a new variable and assign to it, inside of assigning it to a field). I would recommend revisiting your course lecture notes if available. There's an online free PDF called Java Precisely which is a very concise look at Java - the free version is up to Java 5 I think, but it's enough to cover the topics here.

Because you're doing this:
ArrayList <Object> objectArray = new ArrayList <Object> ();
the list there doesn't know what the things inside are, because you said they are Object.
if you make that
ArrayList <BankAccount> objectArray = new ArrayList <BankAccount> ();
it should work like you expect.

If you want to use the methods of BankAccount on the items of your ArrayList, you have to specify that it is a list of BankAccounts. Speficically, the line
ArrayList <Object> objectArray = new ArrayList <Object> ();
should really be
ArrayList <BankAccount> objectArray = new ArrayList <BankAccount>();
You can think of generics as specifying what you have a list of. So for the first example, you can read it as "An ArrayList of Objects." Since you don't know if they are BankAccounts or not, you don't know if you can call settAccNumber() on them.
For the second example, you can read it as "An ArrayList of BankAccounts." In this case you know that they are BankAccounts, so you know that you can call setAccNumber() on them.
Here's a lesson on generics, since you don't seem to quite have the hang of them.
Here's the oracle documentation on them as well.

Other answers correctly suggest using ArrayList<BankAccount>
If (for whatever strange reason) you cannot or do not want to do it, then you need to implicitly cast the retrieved list element to BankAccount type.
Your
objectArray.get(counter).setAccNumber(accountNumber);
will become
((BankAccount)objectArray.get(counter)).setAccNumber(accountNumber);

Related

How to deep copy an object array of multiple classes

As the title suggest, how do I do that? I have searched everywhere in the internet, maybe I didn't search for the right word or something. But please help me.
Object[] FlyingObject = new FlyingObject[3];
FlyingObject[0] = new Helicopter();
FlyingObject[1] = new Airplane();
FlyingObject[2] = new Drone();
Public static Object[] CopyFlyingObject(Object[] C){
Object FlyingObjectCopy = new Object(C.length);
// ...I got no idea how to continue from here
}
Using clone() is not allowed and you aren't allowed to find the name of the class either. I have copy constructor in my other classes but I have no idea how to call it when we're using object, especially with an object array with unknown classes throughout the array.
Edit:
My Subclass code
'''java
int speed;
double price;
Helicopter(){
speed = 0;
price = 0.0;
}
Helicopter(Helicopter c){
speed = c.speed;
price = c.price;
}
public Airplane extends Helicopter{
String brand;
Airplane(){
super();
brand = "";
}
Airplane(Airplane c){
super(C);
brand = c.brand;
}
public String getBrand(){
return brand;
}
}
public Drone{
//practically the same for here
}
'''

Why we can use methods of ArrayList without creating new ArrayList object?

We have to create a object of any class to use their funtionalities unless those are static functionalities. But why we dont need to create a ArrayList object to use its methods like add, contains etc..
ArrayList<Egg> myList = new ArrayList<Egg>();
myList.add(a);
According to my understanding, myList is just variable which holds ArrayList object's reference of type ArrayList class. So again how can we write following without passing object to myList.
ArrayList<Egg> myList;
myList.add(a);
Complete code:
import java.util.ArrayList;
public class DotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
public String checkYourself(String userInput)
{
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}
else
{
result = "hit";
}
}
return result;
}
//TODO: all the following code was added and should have been included in the book
private String name;
public void setName(String string) {
name = string;
}
}
PS
I am referring heads first java book.
The ArrayList reference is being set in the setter method:
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
If this method is not called, and the reference not set before trying to use the ArrayList, then the code will throw a NullPointerException.
Side note: This does not look to be safe code, since it can be easily run incorrectly and so a NPE is easy to create. Better perhaps to set the ArrayList (List is even better) in a constructor.

How do i add together values from all objects of a class in java?

I am trying to retrieve certain values from multiple objects under the same class. I have used a for each loop to iterate through each object, and would like to create an aggregated total, representing the rating and the cost of the item from the objects.
The For Each loop in my parent class:
for (Song songObj : Song.returnSongs()) {
totalSongCost += Double.parseDouble(songObj.getPrice());
totalSongRating += Integer.parseInt(songObj.getRating());
}
The Child class ArrayList meant to store objects:
private int rating;
private String title;
private double price;
private boolean favorite;
private static int counter = 0;
private static ArrayList songArray = new ArrayList();
/**
* Constructor for objects of class Song
*/
public Song()
{
// initialise instance variables
rating = 0;
title = "";
price = 0.0;
counter++;
songArray.add(this);
}
public static ArrayList returnSongs() {
return songArray;
}
When I compile the code I get an error message saying that an object cannot be converted to song. Is there a way to fix this, or an easier way to accomplish the same task?
If you've ever read the docs, you will know that ArrayList is actually a generic class. That means you can give ArrayList a type.
The type of stuff that an array list can store depends on what type you gave it. But if you don't give it any type, it stores Objects! Here,
for (Song songObj : Song.returnSongs()) {
you want to get Song objects from an array list of Object objects, which makes no sense to the compiler. As a result, the error appears.
The solution to this problem is of course, give the array list a type so that it knows what type it should store.
Change this
private static ArrayList songArray = new ArrayList();
to this:
private static ArrayList<Song> songArray = new ArrayList<>();
and change this:
public static ArrayList returnSongs() {
to this:
public static ArrayList<Song> returnSongs() {
ArrayList is a generic class. This means you can specify what class type it is meant to work with. if you change this:
private static ArrayList songArray = new ArrayList();
to this:
private static ArrayList<Song> songArray = new ArrayList<Song>();
Then the ArrayList class will understand that you're working with instances of Song.
Edit: as Jim Garrison pointed out, your returnSongs() method should also be changed to specify the class type in the same way.
public static ArrayList<Song> returnSongs() { ...
It's a little unusual to have the Song class be responsible for keeping track of all of the songs within the application. That seems outside of the responsibility of that class, and perhaps better suited to be handled within a different class, either within your parent class or a new type specially defined.
Additionally, be careful when using types like List and ArrayList. As your compiler will warn you, these require type parameters in angle brackets (i.e. List<Type>). You should make it a habit of addressing all compiler warnings, and of always specifying type parameters for generic types like List. In cases where you don't define your types correctly, things start to default to Object, which leads to the issue you faced here.
Below is an example of what this could look like, restructured to keep the Song class solely for attributes of the song itself:
import java.util.ArrayList;
import java.util.List;
public class Parent {
private static List<Song> songs = new ArrayList<Song>();
private static double totalSongCost = 0.0;
private static int totalSongRating = 0;
public static void main(String[] args) {
populateSongs();
for (Song song : songs) {
totalSongCost += songObj.getPrice();
totalSongRating += songObj.getRating();
}
}
private void populateSongs() {
songs.add(new Song(5, "Hey Jude", 12.5));
songs.add(new Song(4, "Angie", 11.5));
songs.add(new Song(0, "Other", 10.5));
}
}
Your song class would simply be this:
public class Song {
private int rating = 0;
private String title = "";
private double price = 0.0;
public Song(int rating, String title, double price) {
this.rating = rating;
this.title = title;
this.price = price;
}
// Compressed for brevity
public int getRating() { return rating; }
public String getTitle() { return title; }
public double getPrice() { return price; }
}

phonebook with arraylist in java

I want to try a simple implementation of phonebook with arraylist in java.
First I made a class contains what the info. needed and second I want have another class which have methods like getting info and printing them.
and because I want to use array list this is what I've done so far, but the 'print' method keep giving me the error in for loop, is there any one who can help me to optimize my code and why I have this error.
this is the first class :
public class PhoneBook {
long number;
String name;
.
.
.
.
getter() and setter();
}
The second class with methods:
public class PhoneBookMethods {
ArrayList<PhoneBook> phoneBooks = new ArrayList<PhoneBook>();
public void getInfo(PhoneBook phoneBooks)
{
.
.
.
}
public void print(PhoneBook phoneBooks)
{
for (PhoneBook p: phoneBooks) {// this is where I got the error
//foreach not applicable to type 'PhoneBook'
System.out.print(p.getName());
....
}
}
}
In your for-each loop, change
for (PhoneBook p: phoneBooks)
to
for (PhoneBook p: this.phoneBooks)
so that you would be accessing the phoneBooks arraylist, not the argument of the print method.
EDIT:
You can use the "this" keyword to make your code much more "explicit".
For the example, in your case you have an argument called phoneBooks that has the same name as your ArrayList (member variable). So to explicitly differentiate between the two of them, use this.phonebooks to access the member variable phoneBooks(the ArrayList), and use phoneBooks to refer to the argument.
If you want to use instance variable phoneBooks then no need to pass any param in the method print().
public void print()
{
for (PhoneBook p: phoneBooks) {// this is where I got the error
//foreach not applicable to type 'PhoneBook'
System.out.print(p.getName());
....
}
}
OR if you really want to pass param rename the param name
public void print(ArrayList<PhoneBook> phoneBookList)
{
for (PhoneBook p: phoneBookList) {// this is where I got the error
//foreach not applicable to type 'PhoneBook'
System.out.print(p.getName());
....
}
}
public void print(PhoneBook phoneBooks)
Your parameter phoneBooks masks the field (the array) also named phoneBooks. So compiler tries to treat parameter as list and failes.
Actually at first you have some design issues. The way you think what is a PhoneBook is invalid. You should consider a phonebook something holds several phones on it. Therefore, you may have a phone class like below:
public class Phone {
private String number;
private String name;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And a phonebook class responsible for holding those phone objects:
public class PhoneBook extends ArrayList<Phone> {
#Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (Phone phone : this) {
stringBuilder.append("----------------------------\n");
stringBuilder.append("Name:" + phone.getName() + "\n");
stringBuilder.append("Number:" + phone.getNumber() + "\n");
}
return stringBuilder.toString();
}
}
It is a arraylist of Phone, nothing more. Thus, you can add or remove a phone directly via phone book. This is how to use it:
public class MAIN {
public static void main(String[] args) {
Phone myPhone = new Phone();
myPhone.setName("Eray");
myPhone.setNumber("0533XXXXXXX");
Phone girlfriendPhone = new Phone();
girlfriendPhone.setName("Canan");
girlfriendPhone.setNumber("0544XXXXXXX");
Phone yourPhone = new Phone();
yourPhone.setName("Bita Mirshafiee");
yourPhone.setNumber("0599XXXXXXX");
PhoneBook phoneBook = new PhoneBook();
phoneBook.add(myPhone);
phoneBook.add(girlfriendPhone);
phoneBook.add(yourPhone);
System.out.println(phoneBook);
}
}
Finally, this is the output:
----------------------------
Name:Eray
Number:0533XXXXXXX
----------------------------
Name:Canan
Number:0544XXXXXXX
----------------------------
Name:Bita Mirshafiee
Number:0599XXXXXXX

How do I create an object from another class (BlueJ)

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.

Categories