Trying to pass data to an Array List - java

I have to have the code below, pass the data typed in by the user passed to the following method:
public void addPerson(Person p)
{
personList.add(p);
}
and it must be from there added to the array "personList" that is in databse.java (which is posted at the very bottom.
This is what i have so far:
package hartman;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
handleAddPerson(keyboard);
break;
case "2":
Database.printDatabase();
break;
case "3":
handleSearchPerson(keyboard);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
}
private static void handleAddPerson(Scanner keyboard) {
Printer.printAddPersonTitle();
Printer.printPrompt("First Name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt("Last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt("Social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt("Year Born: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
}
static void handleSearchPerson(Scanner keyboard) {
Printer.printSearchPersonTitle();
Printer.printPrompt(" Enter search value: ");
String keyword = keyboard.nextLine();
}
}
here is Person.java for those who wondered.
package hartman;
public class Person {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private int yearBorn;
public Person() {
}
public Person(String firstName, String lastName,
String socialSecurityNumber, int yearBorn) {
}
public int getAge() {
return yearBorn = 2014 - yearBorn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public int getYearBorn() {
return yearBorn;
}
public void setYearBorn(int yearBorn) {
this.yearBorn = yearBorn;
}
}
and here is database.java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
Scanner keyboard = new Scanner(System.in);
private ArrayList<Person> personList;
public Database() {
}
public void addPerson(Person p) {
personList.add(p);
}
public static void printDatabase() {
}
public ArrayList<Person> findPerson(String searchFor) {
Main.handleSearchPerson(keyboard);
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
}
if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
matches.add(p);
}
}
return matches;
}
}

Related

How to display list of accounts and prompt the customer to choose which specific account?

I have been stuck on this for more than 3 days now.
In my main class, ATM, in method verifyCustomer(). When signing in, I'm trying to find a way to ask for a customer ID first. Once verified, then the customers accounts will be listed. After that, the customer will then be prompted to choose which account they want to access, and from there they will be prompted to enter the account number and then the password.
I also have a Gold Account class in which only customers above a certain age "65" are allowed the option to open up. I am having trouble figuring out the logic on how to access that in the initialize() method as well.
I have 3 subclasses to the Account superclass which I didn't include due to there already being too much code.
Any tips?
ATM.java
public class ATM {
private InputReader reader;
private String accountNumber;
private String passcode;
private boolean customerVerified;
private String customerID;
private Bank theBank;
private Customer currentCustomer;
public ATM() {
super();
initialize();
run();
}
public static void main(String[] args) {
new ATM();
}
public void run() {
reader = new InputReader();
boolean exit = false;
while (!exit) {
System.out.println("Welcome to Bank");
System.out.println("Choose one of the following options");
System.out.println("1 - Sign In");
System.out.println("2 - Deposit");
System.out.println("3 - Withdraw");
System.out.println("4 - Display Account Info");
System.out.println("5 - Exit");
System.out.println(">");
int choice = reader.getIntInput();
switch (choice) {
case 1:
verifyCustomer();
break;
case 2:
transactDeposit();
break;
case 3:
transactWithdraw();
break;
case 4:
displayAccountInformation();
break;
case 5:
System.out.println("Thank you for banking at Bank");
System.exit(0);
}
}
}
public void initialize() {
Customer tom = new Customer("Tom", "Smith", "123",70,"A001");
Customer jane = new Customer("Jane", "Smith", "789",18,"A002");
Customer bob = new Customer("Bob", "Smith", "456",32,"A003");
Account tomChequing = new ChequingAccount("CH-123", 0.0,2);
Account tomSavings = new SavingsAccount("SA-123", 50.0);
Account tomGold = new GoldAccount("GL-123",50.0,2.0);
Account janeChequing = new ChequingAccount("CH-789",0.0,2);
Account janeSavings = new SavingsAccount("SA-789", 0.0);
Account bobChequings = new ChequingAccount("CH-456",0.0,5);
Account bobSavings = new SavingsAccount("SA-456", 100.0);
tom.addAccount(tomChequing);
tom.addAccount(tomSavings);
tom.addAccount(tomGold);
jane.addAccount(janeChequing);
jane.addAccount(janeSavings);
bob.addAccount(bobChequings);
bob.addAccount(bobSavings);
theBank = new Bank();
theBank.addCustomer(tom);
theBank.addCustomer(jane);
theBank.addCustomer(bob);
if(currentCustomer.getAge() >= 65) {
currentCustomer.
}
}
public void transactDeposit() {
if (customerVerified) {
System.out.println("Enter the amount to deposit: ");
currentCustomer.getAccountList().addToBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void transactWithdraw() {
if (customerVerified) {
System.out.println("Enter the amount to withdraw: ");
currentCustomer.getAccount().subtractFromBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void displayAccountInformation() {
if (customerVerified) {
System.out.println("Here is your information.");
System.out.println(currentCustomer.toString());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a trasnsaction.");
verifyCustomer();
}
}
public void verifyCustomer() {
System.out.println("Enter your Customer ID");
customerID = reader.getStringInput();
System.out.println("Which account do you want to access?");
System.out.println("Enter Account Number: ");
accountNumber = reader.getStringInput();
System.out.println("Enter your passcode");
passcode = reader.getStringInput();
currentCustomer = Bank.theBank.get(accountNumber);
if (currentCustomer != null) {
if (passcode.equals(currentCustomer.getPasscode()) && customerID.equals(currentCustomer.getCustomerID())) {
customerVerified = true;
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
}
}
Customer.java
import java.util.ArrayList;
public class Customer {
private String firstName;
private String lastName;
private String passcode;
private int age;
private String customerID;
private ArrayList<Account> accounts;
public Customer(String firstName, String lastName, String passcode, int age, String customerID) {
setFirstName(firstName);
setLastName(lastName);
setPasscode(passcode);
setAge(age);
setCustomerID(customerID);
accounts = new ArrayList<>();
}
public void addAccount(Account account) {
accounts.add(account);
}
public ArrayList<Account> getAccountList() {
return accounts;
}
public void setAccountList(ArrayList<Account> account) {
this.accounts = account;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
if (firstName != null && !firstName.trim().isEmpty()) {
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
if (lastName != null && !lastName.trim().isEmpty()) {
this.lastName = lastName;
}
}
public String getPasscode() {
return passcode;
}
public void setPasscode(String passcode) {
if (passcode != null && !passcode.trim().isEmpty()) {
this.passcode = passcode;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID){
this.customerID = customerID;
}
}
Account.java
import java.util.ArrayList;
public class Account {
private String accountNumber;
private double balance;
private boolean active;
protected ArrayList<String> transactionInfo;
public Account() {
super();
}
public Account(String accountNumber, double balance) {
super();
if(accountNumber != null) {
this.accountNumber = accountNumber;
}
setBalance(balance);
active = true;
transactionInfo = new ArrayList<String>();
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public boolean isActive() {
return active;
}
public void setBalance(double balance) {
if(balance >= 0){
this.balance = balance;
}
}
public void setActive(boolean active) {
this.active = active;
}
public void addToBalance(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void subtractFromBalance(double amount) {
if (amount > 0) {
balance -= amount;
}
}
public void addTransactionInfo(String info) {
if(info != null) {
transactionInfo.add(info);
}
}
public void displayAccountRecords() {
if(transactionInfo != null) {
for(String info: transactionInfo) {
System.out.println(info);
}
}
}
}
Bank.java
import java.util.HashMap;
public class Bank {
public static HashMap<String, Customer> theBank;
public Bank() {
super();
theBank = new HashMap<>();
}
public void addCustomer(Customer newCustomer) {
if (newCustomer != null) {
theBank.put(newCustomer.getCustomerID(), newCustomer);
}
}
// use the customerID to access their collection of accounts
public void closeAccount(String customerID, String accountNumber) {
Customer c = theBank.get(customerID);
if(c != null) {
for(Account a: c.getAccountList()) {
if(accountNumber.equals(a.getAccountNumber())) {
theBank.remove(accountNumber);
}
}
//if (theBank.containsKey(customerID)) {
//theBank.get(customerID).getAccountList().remove(accountNumber);
}
}
public static void displayCustomerInformation(Customer customer){
if(customer != null){
System.out.println(customer);
}
}
public static void displayAllCustomers(){
for(Customer customer : theBank.values()){
System.out.println(customer);
}
}
}
You have a HashMap in class Bank and the map key is customer ID. Just add a getCustomer(String) method in class Bank.
public Customer getCustomer(String id) {
return theBank.get(id);
}

Eshop login screen in command line java

i am new to java and i need some help. I want to create a login screen in command line.I have a menu class where at first i want the user to choose if he wants to login, sign up or exit. I am in the sign up case, where he puts his email,password and his identity, which is either Buyer or Owner(they are subclasses of a User class both). Buyer and Owner are two classes of my java project. I have thought of making an extra class Person(subclass to User), with variables String email, int password, User identity and i thought when the user of the eshop writes "Buyer" at the identity variable, the identity becomes buyer, so i can add him to an arraylist
If someone thinks that i should do it differently, i am glad to hear it.
import java.util.ArrayList;
import java.util.Scanner;
public class Menu{
Eshop Eshop = null;
ArrayList<Item> itemsList = new ArrayList<>();
ArrayList<Buyer> buyersList = new ArrayList<>();
User buyer = null;
User Owner = null;
boolean exit;//false
/* public static void main(String[] args){
Menu menu = new Menu();
menu.runMenu();
}
TEMPORARY MAIN TO RUN THE METHODS OF MENU CLASS
*/
Menu()
{
}
Menu(Eshop Eshop, User owner, ArrayList<Item> itemslist, ArrayList<User> buyerslist){
this.Eshop=Eshop;
this.Owner=owner;
itemsList = itemslist;
buyersList = buyerslist;
}
public void runMenu(){
printHeader();
while(!exit){
printMenu();
int choice = getInput();
performAction(choice);
}
}
public int getInput(){
Scanner kb = new Scanner(System.in);
int choice=-1;
while(choice<1 || choice >3){
try{
System.out.print("\n\nEnter your choice:");
choice = Integer.parseInt(kb.nextLine());
}
catch(NumberFormatException e){
System.out.println("Invalid selection plz try again.");
}
}
return choice;
}
public void printHeader(){
System.out.println("+-------------------------------------------+");
System.out.println("| |");
System.out.println("| Welcome to our Eshop Menu |");//+Eshop.getname();
System.out.println("| |");
System.out.println("+-------------------------------------------+");
}
public void printMenu(){
System.out.println("\nPlease make a selection:");
System.out.println("1)Login ");
System.out.println("2)Sign up");
System.out.println("3)Exit!!!!");
}
public void enteremail()
{
Scanner keyboard = new Scanner(System.in);
Scanner codeboard = new Scanner(System.in);
Scanner identityboard = new Scanner(System.in);
String email=null,identity=null;
int code=0;
System.out.println("\n\nEnter your email:");
email=keyboard.nextLine();
System.out.println("\nEnter your code:");
code=codeboard.nextInt();
System.out.println("\nEnter what you are Buyer or Owner");
identity=identityboard.nextLine();
Person p1= new Person(email,code,identity);
if(identity.equals("Buyer"))
buyersList.add(p1);//HERE IS MY PROBLEM HOW I MAKE THE IDENTITY OF PERSON CLASS TO BUYER
}
private void performAction(int choice){
switch(choice){
case 3:
exit = true;
System.out.println("Sta tsakidia!!!");
case 2:
}
}
}//THIS IS THE MENU CLASS
import java.util.ArrayList;
import java.io.*;
public class Person extends User{
int password=0;
String identity;
ArrayList <Person> personList=new ArrayList<Person>();
Person(String email,int password,String identity)
{
this.email=email;
this.password=password;
this.identity=identity;
}
public void Register(Person a)
{
personList.add(a);
}
public void setemail(String email)
{
this.email=email;
}
public String getemail()
{
return email;
}
public void setpassword(int password)
{
this.password=password;
}
public int getpassword()
{
return password;
}
public void setidentity(String identity)
{
this.identity=identity;
}
public String getidentity()
{
return identity;
}
}// THIS IS THE PERSON CLASS
public class Owner extends User
{
private boolean isAdmin;
Owner(String name,String email)
{
this.name=name;
this.email=email;
this.isAdmin=true;
}
}//Owner class
import java.io.*;
public class Buyer extends User
{
private int bonus=0,distance=0;
private double transfercost=0;//metaforika
protected buyerCategory category;//katigoria
private int pointcounter=0;//pointer twn agorwn
enum buyerCategory//Enum gia tin katigoria
{
BRONZE, SILVER,GOLD
}
Buyer(String name, String email,int bonus, ShoppingCart cart,int distance)//DHMIOURGOS
{
this.name=name;
this.email=email;
this.bonus=bonus;
if(bonus>=0 && bonus<100)
category=buyerCategory.BRONZE;
else if(bonus>100 && bonus<200)
category=buyerCategory.SILVER;
else if(bonus<0)
throw new IllegalArgumentException("Bonus has to positive or 0");
else
category=buyerCategory.GOLD;
this.category=category;
if(distance>=0 && distance<10)
transfercost=5;
else if(distance>=10 && distance<100)
transfercost=10;
else if(distance>=100)
transfercost=25;
else
System.out.println("Prepei na baleis thetiko distance");//Thelei exception
/*if(category == buyerCategory.SILVER)
transfercost=transfercost/2;
if(category == buyerCategory.GOLD)
transfercost=0;
*/
}
public void setbuyerCategory(Buyer buyer)
{
int temp;
temp=buyer.getbonus();
if (temp>=0 && temp<100)
category= buyerCategory.BRONZE;
if (temp>100 && temp<200)
category= buyerCategory.SILVER;
//transfercost = transfercost/2;
if (temp>200)
category= buyerCategory.GOLD;
//transfercost = 0;
}
public void awardBonus(Buyer buyer,ShoppingCart cart)
{
cart.CountShoppingCart(cart);
System.out.println("H aksia tis paraggelias sou einai:\t"+cart.calculateNet());
int ten=(int) cart.calculateNet()/10;
/*if (cart.gettotalprice()>=20 && cart.gettotalprice()<50)
temp=buyer.getbonus()+20;
else if(cart.gettotalprice()>=50 && cart.gettotalprice()<100)
temp=buyer.getbonus()+50;
else if (cart.gettotalprice()>100)
temp=buyer.getbonus()+100;
else //ligotero apo 20
temp=buyer.getbonus()+0;
*/
int temp= buyer.getbonus()+ten;
setbonus(temp);
setbuyerCategory(buyer);
if(category == buyerCategory.GOLD)
transfercost=0;
if(category == buyerCategory.SILVER)
transfercost=transfercost/2;
}
public void placeOrder(ShoppingCart so1,ItemOrdered ItemO,int quantity)
{
quantity=ItemO.getquantity();
so1.addItemOrdered(ItemO);
}
public String getname()
{
return name;
}
public String getemail()
{
return email;
}
public void setbonus(int bonus)
{
this.bonus=bonus;
}
public int getbonus()
{
return bonus;
}
public buyerCategory getCategory()
{
return category;
}
public int getdistance()
{
return distance;
}
public double gettransfercost()
{
return transfercost;
}
void print()
{
System.out.println("H stoixeia tou pelati einai:\nCategory:" +getCategory()+"\t\tName:" +getname()+ "\t\tEmail:"+getemail()+"\t\tBonus:" +getbonus()+"\t\tTransfercost:"+gettransfercost());
}
}

Java - Adding 2 objects in an ArrayList

I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()

Project will not display search results

I have this project ive been working on all week and cannot get the search in Main.java in the switch case 3 to work. Any idea why this will not display??
Here it all is :(
Main.Java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
ArrayList<Person> personList = new ArrayList<>();
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
Database.addPerson(personList);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
Printer.printPersonList(personList);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
Database.Java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
static Scanner keyboard = new Scanner(System.in);
private static ArrayList<Person> personList = new ArrayList<Person>();
public Database() {
}
public static void addPerson(ArrayList<Person> personList) {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(person);
}
public static void printDatabase(ArrayList<Person> personList) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personList) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
public static ArrayList<Person> findPerson(String searchFor) {
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
} else if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
} else if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
} else if (String.format("%d", p.getAge()).equals(searchFor)) {
isAMatch = true;
}
if (isAMatch) {
matches.add(p);
}
Printer.printPersonList(matches);
}
return matches;
}
}
Person.Java
package hartman;
public class Person {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private int yearBorn;
public Person() {
}
public Person(String firstName, String lastName,
String socialSecurityNumber, int yearBorn) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
this.yearBorn = yearBorn;
}
public int getAge() {
return yearBorn = 2014 - yearBorn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public int getYearBorn() {
return yearBorn;
}
public void setYearBorn(int yearBorn) {
this.yearBorn = yearBorn;
}
}
Printer.Java
package hartman;
import java.util.ArrayList;
public class Printer {
public static void printWelcome() {
System.out.printf("WELCOME TO PERSON DATABASE!\n");
}
public static void printGoodBye() {
System.out.printf("\nGOOD BYE!!\n");
}
public static void printMenu() {
System.out.printf("\nMain Menu\n");
System.out.printf("---------\n\n");
System.out.printf(" 1. Add a new Person to the database.\n");
System.out.printf(" 2. Print the database.\n");
System.out.printf(" 3. Search for a person in the database.\n");
System.out.printf(" 4. Exit the application.\n");
System.out.printf("\n");
}
public static void printPrintMenu() {
System.out.printf("Print\n\n");
}
public static void printAddPersonTitle() {
System.out.printf("\nAdd Person to Database\n\n");
}
public static void printPrompt(String promptForWhat) {
System.out.printf("%s", promptForWhat);
}
public static void printPersonSaved(Person personSaved) {
System.out.printf("%s", personSaved);
}
public static void printSearchPersonTitle() {
System.out.printf("\nSearch for Person in Database\n\n");
System.out.printf("Enter search value: ");
}
public static void printPersonList(ArrayList<Person> personListToPrint) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personListToPrint) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
}
Any help would be great... im about to break my pc and give up.
The problems is that you are using the static instance from DataBase
ArrayList<Person> personList = new ArrayList<Person>();
I was gonna say follow the rules of OOP click here if you want to learn
But since you already started a lot of coding ill try to answer your problem..
Dont use instance of personList in the DataBase. Just use from the Main class.
here is where the problem started:
for (Person p : personList)
You are using an empty ArrayList from DataBase class..
The one that has data and you are using is from the Main class..
solution:
Remove the
private static ArrayList<Person> personList = new ArrayList<Person>();
from your DataBase then do this in you Main Class
public class Main {
public static ArrayList<Person> personList;
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
personList = new ArrayList<Person>();
and change the for loop to:
for (Person p : Main.personList)
This is what you get when you dont use OOP on your problems its soo ugly and complicated..
Its better when it is object oriented.. P.S. learn that..

How to use more than one method?

So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.
Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.
The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.
Customer:
public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
String custPhone) {
super();
this.customerName = customerName;
this.streetAddress = streetAddress;
this.custCity = custCity;
this.custState = custState;
this.custZip = custZip;
this.custPhone = custPhone;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCustCity() {
return custCity;
}
public void setCustCity(String custCity) {
this.custCity = custCity;
}
public String getCustState() {
return custState;
}
public void setCustState(String custState) {
this.custState = custState;
}
public String getCustZip() {
return custZip;
}
public void setCustZip(String custZip) {
this.custZip = custZip;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
}
Video:
public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
super();
this.videoName = videoName;
this.videoYear = videoYear;
this.copyNum = copyNum;
this.rentalRate = rentalRate;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public int getVideoYear() {
return videoYear;
}
public void setVideoYear(int videoYear) {
this.videoYear = videoYear;
}
public int getCopyNum() {
return copyNum;
}
public void setCopyNum(int copyNum) {
this.copyNum = copyNum;
}
public double getRentalRate() {
return rentalRate;
}
public void setRentalRate(double rentalRate) {
this.rentalRate = rentalRate;
}
Invoice (incomplete) :
import java.util.Scanner;
public class Invoice {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Customer Brandon = new Customer("Brandon James" , "112 Oak Street"
, "CityVille" , "Alabama" , "18229",
"912-2248");
Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
"Metropolis" , "Pennsylvania" , "24057", "241-8009");
Video Easter = new Video("Easter 2", 2002, 4, 2.49);
Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);
if( Prog4.newRental = "Brandon"){
Customer Brandon = newCust
}
}
}
Prog4(incomplete):
import java.util.*;
public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter Customer Name: ");
String newRental = in.nextLine();
System.out.println("Enter Video Name: ");
String vidName = in.nextLine();
System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();
System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}
public String getNewRental() {
return newRental;
}
public void setNewRental(String newRental) {
this.newRental = newRental;
}
public String getVidName() {
return vidName;
}
public void setVidName(String vidName) {
this.vidName = vidName;
}
public String getRentalDate() {
return rentalDate;
}
public void setRentalDate(String rentalDate) {
this.rentalDate = rentalDate;
}
public String getDaysRented() {
return daysRented;
}
public void setDaysRented(String daysRented) {
this.daysRented = daysRented;
}
}

Categories

Resources