"p" cannot be resolved to a variable - java

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();

Related

HashMap returning null after adding values

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!!

Run time binding in java using interfaces

// Item class
import java.io.*;
interface Item {
void read();
void show();
}
class Book implements Item {
String name,author,publication;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the Book:");
name = con.readLine();
System.out.println("Enter Author Name:");
author = con.readLine();
System.out.println("Enter Publication of the book:");
publication = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+name);
System.out.println("Author :"+author);
System.out.println("Publication :"+publication);
}
}
class Dvd implements Item {
String dname,director,category;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the dvd ");
dname = con.readLine();
System.out.println("Enter Director Name");
director = con.readLine();
System.out.println("Enter Category of the dvd: ");
category = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+dname);
System.out.println("Director :"+director);
System.out.println("Category :"+category);
}
}
Library class
import java.io.*;
class Library {
public static void main(String args[]) {
Console con = System.console();
Item arr[] = new Item[2];
Item a;
for(int i=0;i<arr.length;i++) {
System.out.println("Enter Your Choice : < b / d >");
String ch = con.readLine();
switch(ch) {
case "b":
a = new Book();
a.read();
a.show();
break;
case "d":
a = new Dvd();
a.read();
a.show();
break;
default:
System.out.println(" You Enetred The Wrong Choice !!!");
}
}
}
}
As in this code i have created two classes i.e.. Item and Libraryy .
At run time dynamic binding is done successfully but after reading any choice it shows results at the same time and i want to show all results after entering all the choices first .
For storing references i used arrays which stores the refernce of my choice types.
**//Class Item is Fine **
import java.io.*;
interface Item {
void read();
void show();
}
class Book implements Item {
String name,author,publication;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the Book:");
name = con.readLine();
System.out.println("Enter Author Name:");
author = con.readLine();
System.out.println("Enter Publication of the book:");
publication = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+name);
System.out.println("Author :"+author);
System.out.println("Publication :"+publication);
}
}
class Dvd implements Item {
String dname,director,category;
public void read() {
Console con = System.console();
System.out.println("Enter Name of the dvd ");
dname = con.readLine();
System.out.println("Enter Director Name");
director = con.readLine();
System.out.println("Enter Category of the dvd: ");
category = con.readLine();
}
public void show() {
System.out.println("List Of Issued Items");
System.out.println("Name :"+dname);
System.out.println("Director :"+director);
System.out.println("Category :"+category);
}
}
// Class Library
import java.io.*;
class Library {
public static void main(String args[]) {
Console con = System.console();
Item arr[] = new Item[2];
Item a;
for(int i=0;i<arr.length;i++)
{
System.out.println("Enter Your Choice : < b / d >");
String ch = con.readLine();
switch(ch)
{
case "b":
arr[i] = new Book();
arr[i].read();
break;
case "d":
arr[i] = new Dvd();
arr[i].read();
break;
default:
System.out.println(" You Enetred The Wrong Choice !!!");
}
}
for(int i=0;i<arr.length;i++)
arr[i].show();
}
}

How can i log in using a name and a password stored in two different arrays?

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...

ArrayLists (Removing and Changing Elements)

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();

Am I doing this right? ArrayList searching

I have a switch statement that allows you to search for a user in a database. The search is basically just searching for a matching character whether it is numeric or alphabetic. It doesn't seem to be working though, any ideas?
Here 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);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
Here 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 = 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;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
} else if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
}
matches.add(p);
Printer.printPersonList(matches);
}
return matches;
}
}
and here is where printer is doing.
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());
}
You should not be passing personList around everywhere like you are doing Likely, you are not iterating over the copy of personList you think you are doing. Since personList is empty, printPersonList is never called. That is why you get no output.
There is really no reason to have personList in Main.java at all. As the code is written now, the copy of personList you would work with is:
private static ArrayList<Person> personList = new ArrayList<Person>();
in Database.java.
I might suggest a little further refactoring, but I think that should be enough to get you some working code.
In the method findPerson , the variable isAMatch seems did not take effort.
No matter what the value of isAMatch is, the list matches would always add the object p.
So , it may look like this:
if (isAMatch) {
matches.add(p);
}
Also , the code Printer.printPersonList(matches); should be out of the for loop.
By the way , what's the point??
else if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
}

Categories