I know this question has been asked before but I can't understand how to fix this issue. I'm adding values to a HashMap and in setStudent and then when I try to change the value in replaceName but the key doesn't seem to exist.
import java.util.*;
public class Student {
private HashMap<String, List<String>> studentDetails = new HashMap<String, List<String>>();
private HashMap<String, List<String>> studentModules = new HashMap<String, List<String>>();
public void setStudent(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled, List<String> modules) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.put(id, information);
studentModules.put(id, modules);
}
public List<String> getStudentDetails(String x) {
return studentDetails.get(x);
}
public List<String> getStudentModules(String x) {
return studentModules.get(x);
}
public void replaceName(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.replace(id, information);
}
}
My main class is quite long but basically it takes user input to get the values:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner source = new Scanner(System.in);
RecordManager r = new RecordManager();
Module m = new Module();
Student s = new Student();
ChangeName c = new ChangeName();
while (true) {
System.out.println("Please enter the student id:");
r.setId(source.nextLine());
System.out.println("Please enter the student name:");
r.setName(source.nextLine());
System.out.println("Please enter the student address:");
r.setAddress(source.nextLine());
System.out.println("Please enter the student email address:");
r.setEmailAddress(source.nextLine());
System.out.println("Please enter the degree title:");
r.setDegreeTitle(source.nextLine());
System.out.println("Please enter the date enrolled:");
r.setDateEnrolled(source.nextLine());
List<String> a = new ArrayList<>();
while (true) {
System.out.println("Please enter the module name:");
String name = source.nextLine();
m.setName(name);
a = r.addModule(name, a);
m.setTitle(name);
System.out.println("Please enter the module code:");
m.setCode(source.nextLine());
while (true) {
System.out.println("Please enter the module mark (between 1 and 100):");
int mark = source.nextInt();
if (mark > 0 && mark <101) {
m.setMark(mark);
break;
}
else {
System.out.println("Module mark must be between 1 and 100");
}
}
System.out.println("Please enter the module credits:");
m.setCredits(source.nextInt());
m.setModule();
System.out.println("Would you like to enter another module? (Y/N)");
String more = source.next();
if (more.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
r.setModules(a);
s.setStudent(r.getId(), r.getName(), r.getAddress(), r.getEmailAddress(), r.getDegreeTitle(), r.getDateEnrolled(), r.getModules());
r.addStudents(r.getId(), s.getStudentDetails(r.getId()));
System.out.println("Would you like to enter the details for another student? (Y/N)");
String another = source.next();
if (another.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
while (true) {
System.out.println("Full list of students and details (1) \nLookup a student by name (2) \nChange student name (3)");
source.nextLine();
int choice = source.nextInt();
if (choice == 1) {
for (String id : r.getStudents().keySet()) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
}
break;
}
else if (choice == 2) {
System.out.println("Please enter the full name of the student:");
source.nextLine();
String name = source.nextLine();
boolean exists = false;
int i = 0;
for (String id : r.getStudents().keySet()) {
if (s.getStudentDetails(id).get(i).equalsIgnoreCase(name)) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
exists = true;
}
i += 1;
}
if (exists == false) {
System.out.println("Student not found");
}
break;
}
else if (choice == 3) {
System.out.println("Please enter the ID of the student:");
source.nextLine();
String id = source.nextLine();
System.out.println("Please enter the new name:");
String name = source.nextLine();
c.changeName(id, name, s.getStudentDetails(id));
System.out.println(s.getStudentDetails(id));
break;
}
else {
System.out.println("Incorrect selection. Please enter 1, 2 or 3");
}
}
}
}
And finally I have the class to change the name:
import java.util.*;
public class ChangeName {
RecordManager r = new RecordManager();
Student s = new Student();
public void changeName(String id, String newName, List<String> details) {
s.replaceName(id, newName, details.get(1), details.get(2), details.get(3), details.get(4));
}
}
Any help would be greatly appreciated!!
Related
I have looked at similar examples or other programs that call array from another class and it seems like I have done it the correct way but I am still getting errors.
This is where the arrarys are stored:
import java.util.Scanner;
public class DriverProgram {
public static int[] IDs = new int[10];
public static String[] names = new String[10];
public static double[] grades = new double[10];
public static int i = 0;
static Student call = new Student();
public static void main(String[] args){
call = new Student();
Scanner command = new Scanner(System.in);
System.out.println("Please Enter a command(i, r, s, or d): ");
while(command.hasNext()){
char command1 = command.next().charAt(0);
if(command1 == 'i'){
call.AddToArray(IDs[], names[] , grades[], i);
}else if(command1 == 'r'){
call.RemoveFromArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 's'){
call.SortArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'd'){
call.DisplayArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'z') {
break;
}
else System.out.println("Invalid command enter a valid command next time.");
System.out.println("Please Enter a command(i, r, s, or d) or z to finish: ");
}
}
And this is what I am tryign to call the arrays to:
import java.util.Scanner;
public class Student {
public static void AddToArray(int[] IDs, String[] names, double[] grades, int i) {
if (i >= 10) {
System.out.println("You have already inputted 10 students please delete one first.");
} else {
Scanner readin = new Scanner(System.in);
Scanner readinname = new Scanner(System.in);
Scanner readingrade = new Scanner(System.in);
System.out.println("Please enter student ID: ");
IDs[i] = readin.nextInt();
System.out.println("Please enter student name: ");
names[i] = readinname.nextLine();
System.out.println("Please enter student grade: ");
grades[i] = readingrade.nextDouble();
System.out.println(IDs[i] + " " + names[i] + " " + grades[i]);
i++;
for (int j = 0; j < i; j++) {
if (IDs[j] == IDs[i]) {
System.out.println("This student has already been entered.");
}else{
System.out.println("The student has been added");
break;
}
}
}
}
I am not sure what else I need or what I am missing in order to call those arrays.
call.AddToArray(IDs[], names[] , grades[], i);
should be replaced with
call.AddToArray(IDs, names , grades, i);
P.S. Design notes
Student has only static method, so this is utilitly class and should not allowed an instance creation
call.AddToArray() and others static methods should be called as Student.AddToArray()
array is not correct data strucutre where you can add or remove elements. There're more suitable data structures like List or Map.
It's better to use only one instance of Scanner.
This is how you DriverProgram could look like.
public class DriverProgram {
public static void main(String[] args) {
Map<Integer, Student> students = new HashMap<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.println("Please Enter a command [1-5]:");
System.out.println("1. add new student");
System.out.println("2. remove existed student");
System.out.println("3. sort existed students by grades desc");
System.out.println("4. show existed students");
System.out.println("5. exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1)
addStudent(scan, students);
else if (menu == 2)
removeStudent(scan, students);
else if (menu == 3)
sortStudents(students);
else if (menu == 4)
showStudents(students);
else if (menu == 5)
break;
System.err.println("Unknown command. Try again");
}
}
private static void addStudent(Scanner scan, Map<Integer, Student> students) {
if (students.size() == 10) {
System.err.println("You have already inputted 10 students please delete one first.");
return;
}
System.out.print("Please enter student ID: ");
int id = scan.nextInt();
if (students.containsKey(id)) {
System.err.println("This student with this id has already been entered.");
return;
}
System.out.print("Please enter student name: ");
String name = scan.nextLine();
System.out.print("Please enter student grade: ");
double grade = scan.nextDouble();
students.put(id, new Student(id, name, grade));
}
private static void removeStudent(Scanner scan, Map<Integer, Student> students) {
}
private static void sortStudents(Map<Integer, Student> students) {
}
private static void showStudents(Map<Integer, Student> students) {
}
public static final class Student {
private final int id;
private final String name;
private final double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
}
I have to make a program using inheritance and I want to print out what I have inputted. But when I run the program, no error founded, it just gives me an empty blank space. What is wrong with my code? Did I make a mistake in calling the variable?
This is my main code:
package labweek7;
import java.awt.Menu;
import java.util.Scanner;
import java.util.Vector;
public class Main {
Vector<String> menu =new Vector<>();
Scanner scan = new Scanner(System.in);
//Employee emp;
Employee emp = new EmployeeFullTime(null, 0, null, null);
Employee emps = new EmployeePartTime(null, 0, null, null);
EmployeeFullTime ft = new EmployeeFullTime(null, 0, null, null);
EmployeePartTime pt = new EmployeePartTime(null, 0, null, null);
public Main() {
int choice = 0;
int pay;
int time;
int salary;
do{
System.out.println("ABC EMPLOYEE DATA");
System.out.println("=================");
System.out.println("1. Add Employee");
System.out.println("2. View Employee");
System.out.println("3. Resign");
System.out.println("4. Exit");
System.out.print("Choice: ");
choice = scan.nextInt();
scan.nextLine();
switch(choice){
case 1:
String name = "";
do{
System.out.print("Input employee name[must be more than 3 characters]: ");
name = scan.next();
}while(! (name.length()>=3));
emp.empName.add(name);
int age;
do{
System.out.print("Input employee age[>=17]: ");
age = scan.nextInt();
}while(!(age>=17));
emp.empAge.add(age);
String role = "";
do{
System.out.print("Input employee role[Assistant | Programmer](Case Sensitive): ");
role = scan.next();
}while(!(role.equals("Assistant") || (role.equals("Programmer"))));
emp.empRole.add(role);
String type = "";
do{
System.out.print("Input employee type[PartTime | FullTime](Case Sensitive): ");
type = scan.next();
}while(!(type.equals("PartTime")|| type.equals("FullTime")));
emp.empType.add(type);
if(type.equals("PartTime")){
emp = new EmployeePartTime(name, age, role, type);
do{
System.out.print("Input pay per hour[>=10000]: ");
pay = scan.nextInt();
}while(!(pay>=10000));
pt.pays.add(pay);
do{
System.out.print("Input working hour per week[>0]: ");
time = scan.nextInt();
}while(!(time>0));
pt.hours.add(time);
}
else{
emps = new EmployeeFullTime(name, age, role, type);
do{
System.out.print("Input base salary[>=10000]: ");
salary = scan.nextInt();
}while(!(salary>=10000));
ft.salary.add(salary);
}
String status = "active";
System.out.println("Success insert employee data");
System.out.println("");
System.out.println("Please any key to continue...");
scan.nextLine();
break;
case 2:
boolean ans = emp.empName.isEmpty();
if(ans == true){
System.out.println("There is no employee data in the list");
}
else
{
view();
}
}
}while(choice!=4);
}
void view(){
//for(int i=0; i<menu.size(); i++){
System.out.println("Employee no.");
if(emp.empType.equals("FullTime")){
System.out.println("Full Time Employee");
System.out.println("===================");
System.out.println("Status: ");
for(int j=0; j<emps.empName.size(); j++){
// if(emps == null){
// }
// else{
System.out.println("Name: " + emps.empName.get(j));
// }
//System.out.println("Name: " + emps.empName.get(j));
}
for(int m=0; m<emp.empAge.size(); m++){
System.out.println("Age: " + emps.empAge.get(m));
}
for(int n=0; n<emps.empRole.size(); n++){
System.out.println("Role: " + emps.empRole.get(n));
}
for(int o=0; o<ft.salary.size(); o++){
System.out.println("Base salary per month: " + ft.salary.get(o));
}
System.out.println("");
}
else
{
System.out.println("Part Time Employee");
System.out.println("===================");
// System.out.println("Status: " );
// System.out.println("Name: " + emp.empName.get(i));
// System.out.println("Age: " + emp.empAge.get(i));
// System.out.println("Role: " + emp.empRole.get(i));
// System.out.println("Pay per hour: "+pt.pays.get(i));
// System.out.println("Working hour per week: "+pt.hours.get(i));
// System.out.println("Salary per month: "+ pt.pays.get(i) * pt.hours.get(i));
//
}
System.out.println("\n\n");
System.out.println("Press any key to continue...");
}
void resign(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main();
}
}
This is my parent class:
package labweek7;
import java.util.Vector;
public abstract class Employee {
public String name;
public int age;
public String role;
public String type;
Vector<String> empName = new Vector<>();
Vector<Integer> empAge = new Vector<>();
Vector<String> empRole = new Vector<>();
Vector<String> empType = new Vector<>();
public Employee(String name, int age, String role, String type) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
this.role = role;
this.type = type;
}
}
This is my child class 1 :
package labweek7;
import java.util.Vector;
public class EmployeePartTime extends Employee{
int pay;
int hour;
Vector<Integer> pays = new Vector<>();
Vector<Integer> hours = new Vector<>();
public EmployeePartTime(String name, int age, String role, String type) {
super(name, age, role, type);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
This is my child class 2 :
p
ackage labweek7;
import java.util.Vector;
public class EmployeeFullTime extends Employee{
int gaji;
Vector<Integer> salary = new Vector<>();
public EmployeeFullTime(String name, int age, String role, String type) {
super(name, age, role, type);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Did I make mistake in the for loop? Why does my code not printing the inputted items? Any help is appreciated. Thank You.
I have debugged your code in my eclipse work-space.
I'm able to insert the employee data successfully as shown below:
ABC EMPLOYEE DATA
=================
1. Add Employee
2. View Employee
3. Resign
4. Exit
Choice: 1
Input employee name[must be more than 3 characters]: asfds
Input employee age[>=17]: 14
Input employee age[>=17]: 18
Input employee role[Assistant | Programmer](Case Sensitive): Assistant
Input employee type[PartTime | FullTime](Case Sensitive): PartTime
Input pay per hour[>=10000]: 20000
Input working hour per week[>0]: 12
Success insert employee data
But after selecting second option for View Employee I was getting empty output.
ABC EMPLOYEE DATA
=================
1. Add Employee
2. View Employee
3. Resign
4. Exit
Choice: 2
There is no employee data in the list
After debugging it a bit more I came across a condition in Main()
boolean ans = emp.empName.isEmpty();
if(ans == true){
System.out.println("There is no employee data in the list");
} else {
view();
}
The emp.empName is empty here. All Vectors are empty which belong to Employee class.
Vector<String> empName = new Vector<>();
Vector<Integer> empAge = new Vector<>();
Vector<String> empRole = new Vector<>();
Vector<String> empType = new Vector<>();
As a workaround I just changed emp.empName.isEmpty() to emp.name.isEmpty() to resolve the problem. I hope this helps you in identifying the problem.
public class Coach extends Team {
private int Code;
public Coach(String name, String team, int age) {
super(name, team, age);
}
public Coach() {
}
public void setCode(int code) {
this.Code = code;
}
public int getCode() {
return Code;
}
public String code[] = {
"qwe",
"asd",
"zxc"
};
public String CoachName[] = {
"person1",
"person2",
"person3"
};
}
The main class
import com.org.FS.Coach;
import com.org.FS.Team;
import java.util.Scanner;
public class TeamTest {
public static void main(String[] args) {
System.out.println("Welcome to Federation System!! \n\nPlease enter your name:");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("\nHi " + name + " !!\n\nPlease select an option\n 1- Guest and 2- Admin : \n Guest Admin ");
int choice = input.nextInt();
System.out.println("You choose --- " + choice);
switch (choice) {
case 1:
System.out.println("Table Info");
System.out.println("=============================================================");
break;
case 2:
System.out.println(" ==Log in== ");
}
if (choice == 1) {
Card c = new Card();
System.out.println(" ==Players==\n" + c);
System.out.println("==============================================================");
} else if (choice == 2) {
Coach co=new Coach();
System.out.println("Enter username:\n");
name=input.nextLine();
System.out.println("\n\nWelcome " + name + "\nPlease enter your verification code :");
String code1=input.nextLine();
for(int i=0;i<co.CoachName.length;i++) {
if( name.equals(co.CoachName[i]) || code1.equals(co.code[i]) && (!co.getName().equals(co.CoachName[++i]) || !co.code.equals(co.code[++i])) )
System.out.println("Wrong code!\nTry Again!");
else
System.out.println("Success !");
}
}
}
}
my project contains 5 classes named
TeamTest1(the main class)
Team
Players
Coach
and Card
the team class is the superclass and have coach and players as subclasses.
When i run the code and i press 1 the guest it shows only the players information.If i press two Admin,i want to put the name person1 like i have it in the array and the password too.Im very confused if i need to creATE A new array or to use the one i have...
for getting user input repeatedly you can use a while loop like so
int choice = input.nextInt();
while (choice != 3) {
...
choice = input.nextInt();
}
for getting (user,password) pairs you can use a map like so
Map users = new HashMap();
m.put("person1", "qwe");
m.put("person2", "asd");
m.put("person3", "zxc");
and check if the key value match
value = m.get(co.CoachName)
if code.equals(value) ....
Don't forget to use try catch and/or check for integrity of user input and keys exists in map and so...
Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
I have to use a switch statement to allow a user to select what they want to do, if they select "1", it will allow them to add a person to a database. In the switch statement for "1", i am getting a syntax error stating that "p" cannot be resolved to a variable. However, I have tried everything i can possibly think of to get this to work and it will not. any idea?
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(p);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
This is 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;
public Database() {
}
public static void addPerson(Person personList2) {
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(personList2);
}
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;
}
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;
}
}
The compiler cant resolve p to a variable, because you declare p nowhere.
Better solution:
I think its much nicer to do the person creation process directly in the database, so do the following:
Change Database.java to this:
public static void addPerson() {
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);
}
Change first code to:
Database.addPerson();