I'm doing a homework assignment, where we were asked to create a banking system. The first option is to create a customer and to store their information in a customer object. The start of my create_customer() method asks for their name and stores it into a newly create Customer object, but when i call the getName() method, nothing comes back. Here's the initial class Atm which holds all the actions for each option.
import java.util.ArrayList;
public class Atm
{
private ArrayList<Customer> cust;
private int starting_account_number;
private int starting_customer_number;
private String admin_pin;
private int interest_rate;
private int transaction_counter;
ConsoleReader console = new ConsoleReader(System.in);
public Atm() // constructor
{
cust = new ArrayList<>(100);
starting_account_number = 1001;
starting_customer_number = 101;
admin_pin = "abcd";
interest_rate = 5;
transaction_counter = 0;
}
void create_customer()
{
Customer customer = new Customer();
System.out.println("Please input your name: ");
customer.setName(console.readLine());
customer.getName();
while (customer.istrue)
{
System.out.println("Please input a 4 digit alphanumeric PIN: ");
customer.setPin(console.readLine());
if (customer.istrue == false) break;
}
System.out.println("A system generated ID was created for you, it is: ");
String customer_id = String.valueOf(starting_customer_number);
customer.setId(customer_id); // set customer ID
starting_customer_number++; //incrememnt customer ID
System.out.print(customer.getId());
cust.add(customer); //puts the customer object into atm class arraylist
}
Here's the customer class
import java.util.ArrayList;
public class Customer
{
public boolean istrue;
private String name;
private String id; // 3 digits string
private String pin; // 4 digits string
private ArrayList<Account> acct;
private double total_bal; // for all accounts
public Customer() //constructor
{
acct = new ArrayList<>(100);
istrue = true;
name = "NoName";
id = "000";
pin = "0000";
total_bal = 0;
}
// public cal_total_bal() { }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
if (pin.length() != 4)
{
System.out.println("That was not 4 digits, please input a 4 digit alphanumeric PIN: ");
}
else istrue = false;
}
You are calling a method
customer.getName();
But you are not actually doing anything with it.. you might want to print it:
System.out.println(customer.getName());
Related
I have been tasked with writing a code to create 4 classes(Main, Person,Account,Vehicle)and create objects of the Person class as per user requirements, doing so using an array. I had to store data within the array via user input, and retrieve them as per user choice. Which I believe I have successfully done so. One of the two inputs I had to ask from the user were, "Do you have an Account" and "Do you have a vehicle". If the User answers "Yes", I had to pass the object or something as a reference to the Account and Vehicle class to seclude them separately as well, and when the User asks for the People with an Account and Vehicle, It were to print the details of those specific users only.
.
Here is my code below
Main.java:
package com.company;
import java.util.Scanner;
public class Main {
public static int ids;
static int choice = 0;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menus();
}
public static void conditions(int choice){
switch (choice) {
case 1:
int i;
System.out.println("Enter id of person");
i = sc.nextInt();
Person user2[] = new Person[10];
user2[i] = new Person();
user2[i].setArray(i,user2);
//Getters
int k;
System.out.println("Enter id of existing person to retrieve info or press 0 to go to menu");
int l;
l = sc.nextInt();
if (l == 0) {
menus();
}
else {
System.out.println(user2[l].getName());
System.out.println(user2[l].getGender());
System.out.println(user2[l].getAge());
System.out.println(user2[l].isAccount());
System.out.println(user2[l].isVehicle());
}
case 2:
//Call getters
Account a1=new Account();
a1.getArrays();
case 3:
Vehicle v1=new Vehicle();
v1.printArray();
}
}
public static void menus() {
System.out.println("Choose an option");
System.out.println("1.Enter new person details");
System.out.println("2.Does not work(should display people who want an acc only");
System.out.println("3.Does not work(Should display people who have a vehicle only)");
choice = sc.nextInt();
conditions(choice);
}
}
Person.java:
package com.company;
import java.util.Scanner;
public class Person {
private String name;
private int age;
private String gender;
private static String Account;
private static String Vehicle;
Person array[];
public String isAccount() {
return Account;
}
public void setAccount(String account) {
Account = account;
}
public String isVehicle() {
return Vehicle;
}
public void setVehicle(String vehicle) {
Vehicle = vehicle;
}
public Person[] getArray() {
return array;
}
public void setArray(int i,Person[] array) {
this.array = array;
Scanner sc=new Scanner(System.in);
System.out.println("Enter name");
name=sc.next();
array[i].setName(name);
System.out.println("Enter age");
age=sc.nextInt();
array[i].setAge(age);
System.out.println("Enter gender");
gender=sc.next();
array[i].setGender(gender);
System.out.println("Enter Yes if you want an account,No if otherwise");
Account=sc.next();
if(Account=="Yes"){
Account user3[] = new Account[10];
user3[i].setArray(i,this.array);
user3[i] = new Account(i,name,gender,Account);
}
else{
array[i].setAccount("No");
}
System.out.println("Enter Yes if you have a vehicle, No if otherwise");
Vehicle=sc.next();
if(Vehicle=="Yes"){
Vehicle user4[] = new Vehicle[10];
user4[i] = new Vehicle();
user4[i].setArray(i,this.array);
}
else{
array[i].setVehicle("No");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Accounts.java:
package com.company;
public class Account extends Person{
Account[] arrays;
private int ages;
private String names;
private String genders;
private String vehicles;
private String accounts;
Account(int id,String names,String genders,String accounts){
arrays[id].setNames(names);
arrays[id].setAges(ages);
arrays[id].setGenders(genders);
arrays[id].setAccounts(accounts);
}
Account(){
}
public com.company.Account[] getArrays() {
return arrays;
}
public void setArrays(com.company.Account[] arrays) {
this.arrays = arrays;
}
public int getAges() {
return ages;
}
public void setAges(int ages) {
this.ages = ages;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getGenders() {
return genders;
}
public void setGenders(String genders) {
this.genders = genders;
}
public String getVehicles() {
return vehicles;
}
public void setVehicles(String vehicle) {
this.vehicles = vehicles;
}
public String getAccounts() {
return accounts;
}
public void setAccounts(String accounts) {
this.accounts = accounts;
}
public void printArray(){
for(int k=0;k<array.length;k++){
System.out.println(array[k]);
}
}
}
My Vehicle class is the same as Accounts.
-To seclude and print
-I have tried to pass the array from the Person class to the Accounts class and Vehicle, If the User does wish to have an Account and has a Vehicle.
-However, upon printing via for loop or a basic getter, I am met with an Error "this.array is null" which probably means my Array isnt being passed or stored within the Account class.
-Maybe there is a simpler way of secluding and printing them, as per the task I have to implement the use of Abstraction, Arrays, Constructors and Functions.
I am new to Java and the Stackoverflow platform, so please forgive me If the formatting of the question isnt precise. Hope to recieve some detailed help on getting around this.
I'm trying to ask the user for an input in the "doDeposit" method and check if the ID entered matches one from the file, however I get the error "at java.util.Scanner.throwFor(Unknown Source)" when trying to use the Scanner.
The file it my program reads from has the following data:
Brain Adams,51,B10000,3000.5,1
John Waterson,30,B10001,4000.34,0
John Key,61,B10002,56666600,2
Julia Roberts,28,B10003,454545,1,
Tom Cruise,27,B10004,340000000,1
Johnny Tom,54,B10005,230,0
Joe Haldeman,66,B10006,23055.5,0
Charles King,55,B10007,2400.5,0
James Thomson,44,B10008,330.5,0
Cameron Diaz,28,B10009,23000000.6,1
Barak Obama,84,B10010,2000000.4,2
Dustin Hoffman,37,B10011,23000000,1
Robin Williams,72,B10012,22000000.5,1
Russell Crowe,47,B10013,44000000.3,1
Kylie Minogue,28,B10014,10000000.3,1
Paul Keating,41,B10015,4000000.8,2
Lady Gaga,32,B10016,50000000,1
Helen Clark,502,B10017,400000,2
Mikhail Suzenski,32,B10018,0.0,0
Boris Yeltsin,21,B10019,10000000.5,2
My code:
package assignment;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import static java.lang.System.out;
public class Assignment
{
public static void main(String[] args)
{
try
{
new
BankAccountApp("C:/Users/USER/workspace/assignment/data/AssignmentData");
}
catch (IOException ioe)
{
out.printf("Missing file: %sC:/Users/USER/workspace/assignment/data/AssignmentData? \n\n",
new Assignment().getClass().getPackage().getName());
}
}
}
class BankAccountApp
{
private List<BankAccount> accounts;
public BankAccountApp(String filename) throws IOException
{
readAccountData(filename);
displayMenu();
int opt = 0;
try (Scanner input = new Scanner(System.in))
{
while (true)
{
out.print("\nSelect an option: ");
opt = input.nextInt();// format exception if string
if (opt < 0 || opt > 7)
out.println("Invalid. Must be 1 - 7 (or 0 for menu).");
else
break;
}
}
switch (opt)
{
case 0: displayMenu(); break;
case 1: doDeposit(); break;
case 2: doWithdraw(); break;
case 3: displayHighestBalanceAccount(); break;
case 4: displayMostActiveAccount(); break;
case 5: displayAllAccounts("C:/Users/USER/workspace/assignment/data/AssignmentData"); break;
case 6:
{
int total = getTotalTransactions(accounts);
out.println("Total transactions: " + total);
break;
}
case 7: farewell(); return;
}
}
public void readAccountData(String fn) throws IOException
{
accounts = new LinkedList<>();
Path path = new File("C:/Users/USER/workspace/assignment/data/AssignmentData").toPath();
List<String> content = Files.readAllLines(path);
for(String line : content){
String[] items = line.split(",");
String name = items[0];
int age = Integer.valueOf(items[1]);
String accountID = items[2];
double balance = Double.valueOf(items[3]);
int accountType = Integer.valueOf(items[4]);
BankAccount b = new BankAccount(name, age, accountID, balance, accountType);
accounts.add(b);
}
}
public void displayAllAccounts(String fn) throws IOException
{
accounts = new LinkedList<BankAccount>();
Path path = new File(fn).toPath();
List<String> content = Files.readAllLines(path);
for(String line : content){
String[] items = line.split(",");
String name = items[0];
int age = Integer.valueOf(items[1]);
String accountID = items[2];
double balance = Double.valueOf(items[3]);
int accountType = Integer.valueOf(items[4]);
BankAccount b = new BankAccount(name, age, accountID, balance, accountType);
accounts.add(b);
out.printf("---All Bank Accounts---\n");
out.println("Name: "+name);
out.println("Age: "+age);
out.println("Account ID: "+accountID);
out.printf("Account Balance: %f",balance);
out.println("\nAccount Type: "+accountType+"\n");
}
return;
}
public void displayHighestBalanceAccount()
{
BankAccount mostMoney = accounts.get(3);
for(BankAccount b : accounts){
if(mostMoney.getbalance() < b.getbalance()){
mostMoney = b;
}
}
String name = mostMoney.getname();
int age = mostMoney.getage();
String accountID = mostMoney.getaccountID();
double balance = mostMoney.getbalance();
int accountType = mostMoney.accountType();
out.printf("---Bank account with the highest balance---\n");
out.println("Name: "+name);
out.println("Age: "+age);
out.println("Account ID: "+accountID);
out.printf("Account Balance: %f",balance);
out.println("\nAccount Type: "+accountType);
}
public void displayMostActiveAccount()
{
}
public int getTotalTransactions(List<BankAccount> list)
{
return 0;
}
public void doDeposit()
{
out.print("Enter an account ID for deposit: ");
}
public void doWithdraw()
{
}
public void farewell()
{
out.println("Thanks for using the service. Bye!");
}
public void displayMenu()
{
out.println("*********************************");
out.println("* Bank Account Operation Menu *");
out.println("***********************************\n");
out.println("0. Display Menu");
out.println("1. Deposit");
out.println("2. Withdraw");
out.println("3. Display Highest Balance Account");
out.println("4. Display Most Active Account");
out.println("5. Display All Accounts");
out.println("6. Display Total Number of Transactions");
out.println("7. Exit");
}
}
class BankAccount1 extends Person1
{
private String accountID;
private double balance;
private int accountType;
public String getaccountID() {
return accountID;
}
public void setaccountID(String accountID) {
this.accountID = accountID;
}
public double getbalance() {
return balance;
}
public void setbalance(double balance) {
this.balance = balance;
}
public int accountType() {
return accountType;
}
public void setaccountType(int accountType) {
this.accountType = accountType;
}
public BankAccount1(String name, int age, String accountID, double balance, int accountType)
{
super(name, age);
this.accountID = accountID;
this.balance = balance;
this.accountType = accountType;
}
}
class Person1 {
private String name;
private int age;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
public Person1(String name, int age)
{
this.name = name;
this.age = age;
}
}
Any pointers are much appreciated.
I ran your code. I found two errors.
you have a BankAccount1 class and You refers to BankAccount. without "1".
You use a wrong path
See your path is
C:/Users/USER/workspace/assignment/data/AssignmentData
But Path should be like below
C:\\Users\\Menuka\\IdeaProjects\\JavaTest\\src\\AssignmentData`
I'll post full code below.
https://gist.github.com/Menuka5/2af4d16dccbdf780d730fd8bf5ce4e56
I am writing an app that reads a file from the URL when the user input the url address, where the file is located. It will read the data values and then inputs the data values to each class object. When I write the setText command (outside of the while loop), it gets an error when I type e1.getName(). It asks me to initialize e1. I did that, but when I run the app, getName() shows null. I want the name of the employee. So, first here is what the class looks like:
public class Employee {
private String name;
private double salary;
private String id;
private String office;
private String extension;
private int yearsofservice;
//default constructor
Employee(String string, double d, String string2, String string3, String string4, int i)
{
}
//copy constructor
Employee(Employee eData)
{
name = eData.name;
salary = eData.salary;
id = eData.id;
office = eData.office;
extension = eData.extension;
yearsofservice = eData.yearsofservice;
}
//Define the methods
public String getName()
{
//Return the object's name
return name;
}
public void setName(String n)
{
//set the object's name to the given name
name = n;
}
public double getSalary()
{
return salary;
}
public void setSalary(double s)
{
salary = s;
}
public String getId()
{
return id;
}
public void setId(String ID)
{
id = ID;
}
public String getOffice()
{
return office;
}
public void setOffice(String o)
{
office = o;
}
public String getExtension()
{
return extension;
}
public void setExtension(String e)
{
extension = e;
}
public int getYearsOfServ()
{
return yearsofservice;
}
public void setYearsOfServ(int yos)
{
yearsofservice = yos;
}
}
Second, this is the code in the MainActivity or code for the app:
public void displayEmployees(View view)
{
EditText edt1;
TextView tv;
String urlfile;
//Declare three references to Employee object
Employee e1;
Employee e2;
Employee e3;
//Create reference for EditText and TextView
edt1 = (EditText) findViewById(R.id.edit_file);
tv = (TextView) findViewById(R.id.text_main);
//Store the URL address when user input it and assign the input
//to variable (reference) urlfile
urlfile = edt1.getText().toString();
//Use try/catch to check if the file opening on the web succeed
try
{
//Create an URL object that read urlfile
URL file_url = new URL(urlfile);
//try to open the file from the web
Scanner fsc = new Scanner(file_url.openStream());
//As long as there is data to read, continue
//reading the file
while(fsc.hasNext())
{
//tv.append("\n" + fsc.nextLine());//This is for testing to display data
//Create three Employee objects and input the data values
//from urlfile to each object
e1 = new Employee(fsc.nextLine(), Double.parseDouble(fsc.nextLine()),
fsc.nextLine(), fsc.nextLine(), fsc.nextLine(),
Integer.parseInt(fsc.nextLine()));
e2 = new Employee(fsc.nextLine(), Double.parseDouble(fsc.nextLine()),
fsc.nextLine(), fsc.nextLine(), fsc.nextLine(),
Integer.parseInt(fsc.nextLine()));
e3 = new Employee(fsc.nextLine(), Double.parseDouble(fsc.nextLine()),
fsc.nextLine(), fsc.nextLine(), fsc.nextLine(),
Integer.parseInt(fsc.nextLine()));
//e1.setOffice(Integer.parseInt(data));
//...Continue with other class objects with their respective set method
}
tv.setText("The name of the employee: " + e1.getName()); //The error is here!
}
catch(IOException e)
{
tv.setText("Error: Invalid URL Address or File Does Not Exist");
}
}
}
Lastly, the file looks like this (Note: each value is in a seperate line):
Sally L. Smith
086244
100000.00
Ramsey Hall 3814
9976
9
Lucy Bayer
288567
39500.57
Cullimore Hall 100
6000
1
William Harris
732241
120000.00
GITC 165
7533
4
The Employee constructor you use in the while loop does nothing with the data you give him. So you will never get any name on your Employee objects
public Employee(String name , double salary, String id, String office, String extension, int yearsofservice)
{
this.name = name;
this.salary = salary;
this.id = id;
this.office = office;
this.extension = extension;
this.yearsofservice = yearsofservice;
}
It is possible that fsc has no next element(while loop doesn't initiate e1). Write System.out.println("text"); inside while loop and tell if it is being called.
I am new to programming and object oriented design. This is my last requirement to finish my bachelors degree (not in programming). I am so confused with how to make object oriented work, and nothing I look at seems to help.
The assignment is to create a contact list that uses inheritance, polymorphism,and collections. I need a contact list that is stores two types of contacts: business and personal.
1. Prompt to select which contact to add or display.
2. Prompt to allow user to enter the contact info.
3. Prompt that will display the output of a chosen contact back.
I have the following class and subclasses. I am stuck on how I am supposed to read in the inputs to the specific arraylists. I don't even know if the classes are built right either.
Any help would be awesome, I just need to get through this, then I will gladly leave programing to those that know what they are doing.
This is what I have for my Parent Class:
package ooo1;
public abstract class Contact {
private String contactId;
private String firstName;
private String lastName;
private String address;
private String phoneNumber;
private String emailAddress;
public Contact(String contactId,String firstName,String lastName, String address, String phoneNumber, String emailAddress)
{
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}
public void setContactId(String input){
this.contactId = input;
}
public String getContactId(){
return contactId;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getLastName(){
return lastName;
}
public void setAddress(String input){
this.address = input;
}
public String getAddress(){
return address;
}
public void setPhoneNumber(String input){
this.phoneNumber = input;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setEmailAddress(String input){
this.emailAddress = input;
}
public String getEmailAddress(){
return emailAddress;
}
void displayContact(){
System.out.println("Contact ID:" + contactId + " First Name:" + firstName + " Last Name:" + lastName);
System.out.println("Address:" + address);
System.out.println("Phone Number:" + phoneNumber);
System.out.println("Email Address:" + emailAddress);
}
}
This is one of my subclasses:
package ooo1;
public class PersonalContact extends Contact {
private String dateofBirth;
public PersonalContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String dateofBirth){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.dateofBirth = dateofBirth;
}
public void setDateofBirth(String input){
this.dateofBirth=input;
}
public String getDateofBirth(){
return this.dateofBirth;
}
}
This is my other subclass:
package ooo1;
public class BusinessContact extends Contact {
private String jobTitle;
private String organization;
public BusinessContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String jobTitle, String organization){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.jobTitle = jobTitle;
this.organization = organization;
}
public void setJobTitle(String input){
this.jobTitle = input;
}
public String getJobTitle(){
return this.jobTitle;
}
public void setOrganization(String input){
this.organization = input;
}
public String getOrganization(){
return this.organization;
}
}
This is what I have for Main which is so wrong at this point I believe:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
ArrayList<PersonalContact> personalList = new ArrayList<PersonalContact>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
}
}
You have the pieces in place you just need to put them together. First, think about the List being used. It is supposed to hold both types of contacts, however its type argument is using the derived type PersonalContact. Instead use the base class Contact
List<Contact> contacts = new ArrayList<Contact>();
Next it appears you start to gather the information about the contact from the end user via the console. Before doing this you may want to ask what type of contact is being entered, maybe give the option to enter 1 for a personal contact or 2 for a business contact. Then collect the information specific to the type of contact they chose.
Scanner input = new Scanner(System.in);
System.out.println("Please enter Specify the contact type (1 Personal, 2 Business) : ");
int contactType = input.nextInt();
//collect data common to both types
if(contactType == 1){
//collect information specific to personal
} else if(contactType ==2){
//collect information specific to business
}
Next you need to turn the data you collected into the actual objects, using a the constructors. This will need to be done conditionally and could actually be a part of the last section if done properly.
Contact contact;
if(contactType == 1){
contact = new PersonalContact(/*arguments here*/);
} else{
contact = new BusinessContact(/*arguments here*/);
}
Then finish up by adding the contact to your list:
contacts.add(contact);
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
/**
*
* #author Arijit
*/
public class Contact {
private String name;
private int number;
public Contact(int number,String name) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public static Contact createContact(int number, String name){
return new Contact(number,name);
}
}
This is the Contact class, which is governed by a contact name and a contact number. Next we will design the MobilePhone class which will have a number(optional) and an arraylist of contacts.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
import java.util.ArrayList;
/**
*
* #author Arijit
*/
class MobilePhone1 {
public int mynumber;
public ArrayList < Contact > contacts;
public MobilePhone1(int mynumber) {
this.mynumber = mynumber;
this.contacts = new ArrayList < Contact > ();
}
public Boolean addContact(Contact contact) {
if (findPosition(contact) >= 0) {
System.out.println("Contact already is phone");
return false;
} else {
contacts.add(contact);
}
return true;
}
public ArrayList < Contact > getContacts() {
return contacts;
}
public void updateContact(Contact oldContact, Contact newContact) {
if (findPosition(oldContact) >= 0) {
contacts.set(findPosition(oldContact), newContact);
} else {
System.out.println("Contact does not exist");
}
}
public void removeContact(Contact contact) {
if (findPosition(contact) >= 0) {
contacts.remove(findPosition(contact));
} else {
System.out.println("No contact");
}
}
public int searchContact(Contact contact) {
int position = findPosition(contact);
if (contacts.contains(contact)) {
System.out.println("Item found at position");
return position;
}
System.out.println("Not found");
return -1;
}
private int findPosition(Contact contact) {
return this.contacts.indexOf(contact);
}
private int findPosition(String name) {
for (int i = 0; i < contacts.size(); i++) {
Contact contact = this.contacts.get(i);
if (contact.getName().equals(name)) {
return i;
}
}
return -1;
}
}
public class MobilePhone {
public static void main(String args[]) {
Boolean quit = false;
int choice = 0;
java.util.Scanner sc = new java.util.Scanner(System.in);
MobilePhone1 phone = new MobilePhone1(98312);
//Contact newcontact = Contact.createContact(12345,"Arijt");
while (!quit) {
System.out.println("Enter your choice");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 0:
System.out.println("Enter the number of Contacts");
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
int phoneNumber = sc.nextInt();
System.out.println("Enter Name");
sc.nextLine();
String name = sc.nextLine();
Contact newcontact = Contact.createContact(phoneNumber, name);
phone.addContact(newcontact);
}
break;
case 1:
int size = phone.getContacts().size();
System.out.println(size);
for (int i = size - 1; i >= 0; i--) {
phone.removeContact(phone.getContacts().get(i));
}
System.out.println(phone.getContacts().isEmpty());
break;
case 2:
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.searchContact(phone.getContacts().get(i)));
}
break;
case 3:
//Contact newcontact1 = Contact.createContact(12345,"Buzz");
System.out.println("Enter the Contact name you want to update");
String oldContactName = sc.nextLine();
for (int j = 0; j < phone.getContacts().size(); j++) {
if (phone.getContacts().get(j).getName().equals(oldContactName)) {
System.out.println("Enter the new Contact name");
String newName = sc.nextLine();
System.out.println("Enter the new Contact number");
int newNumber = sc.nextInt();
phone.updateContact(phone.getContacts().get(j), Contact.createContact(newNumber, newName));
} else {
System.out.println("You are looking for the wrong contact");
}
}
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.getContacts().get(i).getName() + "," + phone.getContacts().get(i).getNumber());
}
break;
case 4:
if(phone.getContacts().isEmpty()){
System.out.println("Emtpty contact list");
}
else {
System.out.println("Contact list");
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println("Name: "+phone.getContacts().get(i).getName() + ",Phone Number: " + phone.getContacts().get(i).getNumber());
}
}
break;
case 6:
System.out.println("Enter 0 for adding contact\n");
System.out.println("Enter 1 for removing every contact\n");
System.out.println("Enter 2 for searching contact\n");
System.out.println("Enter 3 for updating contact\n");
System.out.println("Enter 4 for viewing the contact list\n");
System.out.println("Enter 6 for exiting\n");
System.out.println("Enter 5 to see the instrusctions again\n");
break;
case 5:
quit = true;
break;
}
}
}
}
I'm here with my classes, my software is almost done after finishing last two things I will continue to GUI development. Anyway, here is my code:
public class Team
{
private String clubName;
private String preName;
private ArrayList<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<Branch> getBranches() { branches = new ArrayList<Branch>(branches);return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<Branch> branches) { this.branches = new ArrayList<Branch>(branches); }
}
public class Branch
{
public ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() {players =new ArrayList<Player>(players); return players; }
public void setPlayers(ArrayList<Player> players) { this.players =new ArrayList<Player>(players); }
public String toString() {
return "Branches [" + brName + "]";}
}
public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;
public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}
public Player(){}
public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }
public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
public String toString() {
return "Player [name=" + name + ", number=" + number + ", pos=" + pos
+ ", salary=" + salary + "]";
}
}
//TEST
String p1,p2;
int a1,a2;
String t, br;
System.out.print("Enter player name : ");
p1 = input.readLine();
System.out.print("Enter player position : ");
p2 = input.readLine();
System.out.print("Enter player salary : ");
a1 = Integer.parseInt(input.readLine());
System.out.print("Enter player number : ");
a2 = Integer.parseInt(input.readLine());
players[pCount].setName(p1);
players[pCount].setPos(p2);
players[pCount].setSalary(a1);
players[pCount].setNumber(a2);
ptmp.add(players[pCount]);
pCount++;
System.out.print("Enter the branch of player : ");
br = input.readLine();
int fff=0;
for(int i = 0; i<brCount;i++)
{
if(br.equals(myBranch[i].brName)==true){
myBranch[i].setPlayers(ptmp);fff=i;}
}
MY FIRST QUESTION : I'm trying to add a player to my system. When a player added I can easily add it to Branch class too and connect them. But I can't do it for Players' club. I mean I want to display which player plays in which club. But I can't do it.
MY SECOND QUESTION : Deleting a player is problem too. When I delete player it should be deleted everywhere. But couldn't figured that out.
In the test, you can see the display function I tried. It works fine for Branch-Player. And I wanna add Team connection too. Team-Branch-Player should be connected.
Q1: It depends how efficiently you want to do your searches.. for now, since you don't store back references you have to first search in which branch is your player and then search which is the club that contains your branch.
With good equals method for your Branch and Player class this is trivial:
for (Team t : teamList)
{
if (t.branches.contains(player))
return true;
}
return false;
But this won't be efficient since you'll have a O(n*m) complexity where n is the team size and m is the average branch size.
If you want something more efficient I'd suggest you to store backreferences inside your classes, you can have your Player class with two attributes
Branch currentBranch
Team currentTeam
and you can set them while you add the player to a branch/team.
Otherwise you can keep a separate HashMap that maps every player to his branch/team. Less memory efficient but quite straightforward.
Q2: to remove the Player from his branch/team you just have to know in which one he stays.. (using the answer to Q1), then before removing from players you just remove it from the corresponding branch/team:
Branch b = findWhichBranch(player);
Team t = findWhichTeam(player);
b.remove(player);
t.remove(player);
players[index] = null;
Of course if branch is implied by team you will just remove it from the branch, since there's no direct association between a player and a team.