print toString() from another class - java

I asked a question earlier on this same project but I'm still having issues that I can't get through.
The project has a Person class, Validator class, Customer class, and Employee class. The Person class stores data about the person (name, email) the Customer class extends the person class and adds a customer number to the toString method. The Employee class also extends the Person class and extends a social security number to the toString method by overriding it.
At the bottom of the page I am trying to print the toString methods from my customer class OR my employee class. I want to make sure I am printing the right class based on what the user selected (if they are entering customer info or employee info)
The assignment specifically says "To print the data for an object to the console, this application should use a static method named print that accepts a Person object."
I think I have it started but I'm getting all kinds of red lines under what I have coded. Starting around the
public void toString()
line down towards the bottom.
I'm starting to think I am getting deeper into trouble by looking it up online so if someone can help me through it I would be greatful. My book doesn't show much on how to do this and all of the examples it shows seem to create the input and then print it but I'm trying to get the input from a user so I'm getting confused.
import java.util.Scanner;
public class PersonApp
{
public static void main(String[] args)
{
//welcome user to person tester
System.out.println("Welcome to the Person Tester Application");
System.out.println();
Scanner in = new Scanner(System.in);
//set choice to y
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//prompt user to enter customer or employee
System.out.println("Create customer or employee (c/e): ");
String input = in.nextLine();
if (input.equalsIgnoreCase("c"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
String custNumber = Validator.getString(in, "Customer number: ");
Customer customer = new Customer(firstName, lastName, email, custNumber);
}
else if(input.equalsIgnoreCase("e"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
int empSoc = Validator.getInt(in, "Social security number: ");
Employee employee = new Employee(firstName, lastName, email, empSoc);
}
public void toString()
{
Person p;
p = c;
System.out.println(c.toString());
p = e;
System.out.println(e.toString());
}
System.out.println("Continue? y/n: ");
choice = in.nextLine();
System.out.println();
}
}
}

You can't define methods inside another method. The way you have the brackets, toString is defined inside main, which is illegal.
Also, you can't have toString return void, since it overrides the toString method from Object. Rename your method or have it return a String.

Your toString method needs to be moved out of your main method. It also needs to return a string. You'll probably have to call the method by some other name. Also, if Employee and Validator are in a separate package structure, you'll have to import that

Related

Login and seperate menus for two different types of user

I'm new to java and programming. I am stuck on one section of an assignment given to me in which I have to create a login for two different types of user which will display two different menus depending on which login is used. I am using Eclipse and the console.
The two different types of user are Boss and Worker and they must login using a username and password. The Boss menu must have the following menu options after logging in:
Setup Worker Schedule
View Worker Schedule
Move Worker
The Worker menu must have the following menu options after logging in:
View Schedule
I'd really appreciate any help with this, thanks in advance.
EDIT:
Okay, so I now have the following code:
import java.util.Scanner;
public class Depot {
public static void main(String[] arguments){
String bossName;
String bossPassword;
String workerName;
String workerPassword;
System.out.println("Enter your name: ");
Scanner authenticate = new Scanner(System.in);
String userName = authenticate.nextLine();
System.out.println("Your username is " + userName);
System.out.println("Enter your password: ");
String passWord = authenticate.nextLine();
System.out.println("Your password is " + passWord);
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
int selection;
Scanner bossMenu = new Scanner(System.in);
System.out.println("1. Setup Worker Schedule");
System.out.println("2. View Worker Schedule");
System.out.println("3. Move Worker");
System.out.println("4. Quit");
do {
selection = bossMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
else if (selection == 2) {
System.out.println("2");
}
else if (selection == 3) {
System.out.println("3");
}
else {
System.out.println("4");
}
}
while(selection != 4);
bossMenu.close();
}
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
int selection;
Scanner userMenu = new Scanner(System.in);
System.out.println("1. View Worker Schedule");
System.out.println("2. Quit");
do {
selection = userMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
}
while(selection != 2);
userMenu.close();
}
}
}
However, the following two lines of code are giving me an error:
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
and
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
bossName, bossPassword, workerName and workerPassword may not have been initialized?
First, get the credentials through using the Scanner, here is a basic way to construct a Scanner object, you will need to have the following import statement at the very beginning of your code, before anything else:
import java.util.Scanner;
To create a Scanner, do the following:
Scanner scannerName = new Scanner(System.in);
That tells the Scanner to read from the input stream, which will be the keyboard. To get data from the Scanner, first prompt the user for the data you need, then use one of the Scanner's .next___ methods to retrieve the input and store in a variable. I'm not going to tell you which one to use, check out the Scanner page in the Java API and see if you can figure it out on your own.
It should look something like this:
System.out.println("Enter your name");
String userLoginString = scannerName.next____();
System.out.println("Enter your password");
String userPasswordString = scannerName.next____();
Once you have the credentials stored in String variables, I'll use userLoginString and userPasswordString as examples, you will need to validate these credentials against some stored values. So, create String variables bossName, bossPassword, workerName, workerPassword.
Once you have the user's credentials, I would perform validation on these login credentials. You could do that using the logical operators and methods of the String class, like so:
if (userLoginString.equals(bossName) && userPasswordString.equals(bossPassword)) {
// print the boss menu
}
else if (userLoginString.equals(workerName) && userPasswordString.equals(workerPassword)) {
// print the user menu
}
The logical && ("and") operator will ensure that the correct menu will be displayed only if the user's credentials match the stored credentials. If the user enters the correct name (boss or worker) but the wrong password (or vice-versa), the statements inside the braces will NOT execute.
UPDATE Here is a commented version of your code so far with some hints as to how to make it better. It will compile and run fine if you just provide values for the String variables at the top, but I have some more suggestions to make it a little nicer:
import java.util.Scanner;
public class Depot {
public static void main(String[] arguments){
// you need to initialize these to some value or else there is
// nothing to compare them with. I tried some dummy values and
// your code worked as expected, as long as the user entered the
// correct values in the prompt.
String bossName;
String bossPassword;
String workerName;
String workerPassword;
// you can just use one Scanner for the whole program, since they are
// both just reading input from the standard input stream. Replace the
// other Scanners with "input" and close "input" at the end
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
// not needed
Scanner authenticate = new Scanner(System.in);
String userName = authenticate.nextLine();
System.out.println("Your username is " + userName);
System.out.println("Enter your password: ");
String passWord = authenticate.nextLine();
System.out.println("Your password is " + passWord);
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
// this could be declared at the top of the program instead of
// redeclaring in the if...else
int selection;
Scanner bossMenu = new Scanner(System.in);
System.out.println("1. Setup Worker Schedule");
System.out.println("2. View Worker Schedule");
System.out.println("3. Move Worker");
System.out.println("4. Quit");
do {
selection = bossMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
else if (selection == 2) {
System.out.println("2");
}
else if (selection == 3) {
System.out.println("3");
}
else {
System.out.println("4");
}
} while(selection != 4); // this is usually here
bossMenu.close();
}
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
// this could be declared at the top of the program instead of
// redeclaring in the if...else
int selection;
// don't need this one, just use "input" Scanner
Scanner userMenu = new Scanner(System.in);
System.out.println("1. View Worker Schedule");
System.out.println("2. Quit");
do {
selection = userMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
} while(selection != 2); // this is usually here
// you would close the "input" Scanner here
userMenu.close();
}
}
}
UPDATED AGAIN!!! A better way to implement the Boss and Worker would be through using inheritance and polymorphism. Start with an abstract superclass that has common characteristics of the Boss and Worker. I'll call this the Employee superclass. It has firstName, lastName, and password instance variables, and you should add getters and setters for each:
// abstract class, CANNOT be instantiated but can be used as the supertype
// in an ArrayList<Employee>
public abstract class Employee {
private String firstName;
private String lastName;
private String password;
public Employee() {
// don't have to do anything, just need this so you can instantiate
// a subclass with a no-arg constructor
}
// constructor that takes only the name of the Employee
public Employee(String firstName, String lastName) {
this(firstName, lastName, null);
}
// constructor that takes name and password
public Employee(String firstName, String lastName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// and so on, for the lastName and password....
// you must implement this specifically in any subclass!
public abstract void getMenu();
}
Then, your Boss and Worker classes could extends this Employee class and they would have all of the same methods and instance variables. You just must provide an overridden getMenu() method in each, since that one was abstract in the Employee class. Here is a sample of what your Boss class should look like, you need to implement the getMenu() yourself and the Worker class:
public class Boss extends Employee {
// notice we don't need the instance variables in the class declaration,
// but they are here since they are part of Employee
public Boss() {
// don't need to do anything here, just allows no-arg constructor
// to be called when creating a Boss
}
// just calls the superclass constructor, could do more if you want
public Boss(String firstName, String lastName) {
super(firstName, lastName);
}
// just calls the superclass constructor, could do more if you want
public Boss(String firstName, String lastName, String password) {
super(firstName, lastName, password);
}
#Override
public void getMenu() {
// put the print statment for Boss's menu here
}
// don't need to re-implement other methods, we can use them since
// they are part of the superclass
}
Once you have the Employee, Worker, and Boss classes, you're ready to try and re-write your program to Objects in place of simple variables as you were doing before. Here is an example of how that would get started:
import java.util.Scanner;
public class EmployeeTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// can make workers and bosses able to be processed polymorphically
// by assinging their references to Employee variables, since
// and Employee is the supertype of each, a Worker "is an" Employee
// and a Boss "is an" Employee.
Employee worker1 = new Worker("Bob", "Worker");
Employee worker2 = new Worker("Sue", "Bush", "Password1");
Employee worker3 = new Worker();
Employee boss1 = new Boss("Jenny", "Boss");
Employee boss2 = new Boss("Bill", "OtherBoss", "Password2");
Employee boss3 = new Boss();
// if you're going to have a lot of workers and bosses, and you don't
// need named variables for each because their info will be included
// in their constructors, you could do this
Employee[] employees = {new Worker("Bob", "Bailey", "myPassword"),
new Worker("Sue", "Sarandon", "123Seven"),
new Boss("Jenny", "Strayhorn", "hardPassword"),
new Boss("Billy", "MeanGuy", "pifiaoanaei")};
// then, you could iterate through this list to check if a password
// entered matches a firstName, lastName, and password combination
// for ANY type of employee in the array, then call the getMenu()
// method on that employee, like so: (This could all be in a loop
// if you wanted to process multiple Employees...)
System.out.println("Enter firstName:");
// you figure out which Scanner method to use!
String firstName = input._____();
System.out.println("Enter lastName:");
String lastName = input._____();
System.out.println("Enter password:");
String password = input._____();
// figure out what get____() method of the Employee class
// needs to be called in each case, and what it should be
// compared to with the .equals() method.
for (int i = 0; i < employees.length; i++) {
if (employees[i].get______().equals(______) &&
employees[i].get______().equals(______) &&
employees[i].get______().equals(______)) {
// if all of those conditions are true, print the menu
// for this employee
employees[i].get_____();
// you could do more stuff here....
// breaks out of the loop, no need to check for anymore employees
break;
}
}
}
}

Generate non repeating numbers to add to customerNumber int variable

I'm creating a banking app and I need to generate a customer number starting from number 1, keeping track of the number so that it won't repeat itself each time I enter the loop and store it into an int variable that I can use to collect the value and pass it to the customerNumber variable outside the loop. I've tried a few things like arraylists and arrays, but I was getting troubles in passing the values to the variable I wanted. Thanks in advance and sorry for my terrible noobishness...I'm new in programming... Here's what I've got so far:
import java.util.ArrayList;
public class Bank{
public void addCustomer(String name, int telephone, String email, String profession) {
ArrayList customerList = new ArrayList();
Customer customer = new Customer();
customerList.add(customer);
}
}
public class Customer{
private String name;
private int telephone;
private String email;
private String profession;
private int customerNumber;
public Customer() {
}
}
public class Menu {
Scanner sc = new Scanner(System.in);
Bank bank = new Bank();
private void createCustomer() {
String name, email, profession;
int telephone, customerNumber;
System.out.println("Enter the customer's number: ");
name = sc.nextLine();
System.out.println("Enter the customer's telephone: ");
telephone = sc.nextInt();
System.out.println("Enter the customer's email: ");
email = sc.nextLine();
System.out.println("Enter the customer's profession: ");
profession = sc.nextLine();
bank.addCustomer(name, telephone, email, profession);
}
}
One thing you can do is create a singleton class, and request a number each time you need one. The singleton class keeps a list of the numbers that have been used already, and thus can return a number that has not been used before.
If you need also to generate new numbers after your application is restarted, then you can store all numbers in a file, and read that file whenever needed.
A singleton class, is a class that can have max 1 instance. You can achieve this by making the constructor private, and creating a public static method (usually called something like getInstance() ) to get an instance of this class. This getInstance() returns the ref to the only instance, and if no instance was created yet, it first creates one.
Then, this only instance knows all account numbers in use (inyour case), regardless how often an instance of this class is requested.
The responsibility of this class is to maintain the account nrs: create a nr, print them, save them, read them, ...
Example:
private AccoutnNr singleInstance;
private AccountNr(){
}
public AccountNr getInstance(){
if (singleInstance == null) {
singleInstance = new AccountNr();
}
return singleInstance;
}
public int getAccountNr{
// do whatever is needed to create an account nr
}
more methods if you need to do more than creating account numbers

Dynamic object creation from user input

I have a two classes, Student containing some basic info, and Course, containing some basic info and an ArrayList of Student objects. I want to dynamically (from user input) populate new instances of both classes. For example, user is prompted for course name, teacher and asked if they want to add students to the course. When done with the course and all the students' information, the loop goes back to asking to add another course.
What I do is, create a Course object and then add students. I manage Student objects by just creating them after collecting user unput with courseInstance.addStudent(new Student(name, age, phone)). It all works well for one course, but how do I manage multiple Course object, dynamically created from input?
Here is a code example:
public static void main(String[] args) {
// TODO code application logic here
Course course = new Course();
Scanner in = new Scanner(System.in);
String ans;
String name;
String gender;
String phone;
int age;
System.out.print("Enter course name: ");
ans = in.nextLine();
course.setName(ans);
System.out.print("Enter teacher name: ");
ans = in.nextLine();
course.setTeacher(ans);
while (true) {
System.out.print("Add student (yes or exit): ");
ans = in.nextLine();
if (ans.equals("exit")) {
break;
}
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter age: ");
age = in.nextInt();
in.nextLine();
System.out.print("Enter gender: ");
gender = in.nextLine();
System.out.print("Enter phone number: ");
phone = in.nextLine();
course.addStudent(new Student(age, name, phone, gender));
}
in.close();
System.out.print(course);
}
How about having a List of Course objects, and asking (in your while(true) loop) what course each student is registering to?
Create a List which you can populate with courses like this:
ArrayList<Course> courses = new ArrayList<Course>();
When a student enters a name from the course, check if the course exists in the array. If not, add it to the array, else get it from the array and add the student.
Since the Name seems to be the primary attribute to identify a course, you should override the equals(Object o) method of course so it compares the two names of the courses.
public boolean equals(Object o){
return this.getName().equals((Course)o.getName());
}
Then you can simply have a List to store your courses and ask the list if it contains a specific course or not. If not you can add it to the list, otherwise you can add students or teachers to the already existing course.
EDIT: It should be getName() on both courses

<identifier> expected when creating an array?

I am writing an airline program that will allow the user to input names and meal choice for each seating section economy, business, and first. I am trying to save all the names and meals into an array. but I am getting a syntax error.
I get expected message when I implement my flyer array.
I have looked on stack overflow. From what I can tell it should be ok to initialize my array this way.
Thanks for any help.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Flyers
{
public Flyers()
{
}
public List<String> seat = new ArrayList<>();
int numberOfFlyers;
int numberOfMeals;
String name;
String meal;
String[][] flyer;
public void addEconomyFlyer()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
numberOfFlyers = in.nextInt();
flyer = new [numberOfFlyers][numberOfFlyers];
}
}
I want each [][] to have the same number of items that is equal to the number of people on the plane. Then I will add a nested for loop that will add a name for each of the flyers, and a meal choice. ultimately i need to be able to print out the array Name and their Meal choice.
Almost, the issue here is you haven't specified a type for the array.
flyer = new [numberOfFlyers][numberOfFlyers];
should probably be
flyer = new String[numberOfFlyers][numberOfFlyers];
However that doesn't make a lot sense. One solution is to use,
flyer = new String[numberOfFlyers][2];
where 0 is name and 1 is meal. But, really you should probably have a flyer POJO,
flyer = new Flyer[numberOfFlyers];
Where Flyer might look something like,
class Flyer {
Flyer(String name, String mealType) {
this.name = name;
this.mealType = mealType;
}
String name;
String mealType;
public String toString() {
return "Name: " + name + ", Meal: " + mealType;
}
}
Then you can create new Flyer(s) and call toString() in your loop. You might also choose to add getter and setter functions for name and mealType.
change :
flyer = new [numberOfFlyers][numberOfFlyers];
to:
flyer = new String[numberOfFlyers][numberOfFlyers];
Scanner class
Scan.scanner.scan
You need scan it!!!!
identifier = here
This trickes computer in think identifier there! YES! WORK!

Email method not working

Hey i have an EmployeeStore which i have used a hashmap for this. The variables that the map stores are email name and id. I have a method called SearchByEmail but there is a problem with this. The method returns false when the user inputs a correct employee email into the UI.
Here is my code:
This is in the MainApp
case 2:
System.out.println("Search by Email.");
Employee employeeSearchEmail = MenuMethods.userInputByEmail();
Store.searchByEmail(employeeSearchEmail.getEmployeeEmail());
MenuMethods
//Imports
import java.util.Scanner;
//********************************************************************
public class MenuMethods
{
private static Scanner keyboard = new Scanner(System.in);
//Methods for the Company Application menu.
//Method for validating the choice.
public static int getMenuChoice(String menuString, int limit, String prompt, String errorMessage)
{
System.out.println(menuString);
int choice = inputAndValidateInt(1, limit, prompt, errorMessage);
return choice;
}
//********************************************************************
//This method is used in the getMenuChoice method.
public static int inputAndValidateInt(int min, int max, String prompt, String errorMessage)
{
int number;
boolean valid;
do {
System.out.print(prompt);
number = keyboard.nextInt();
valid = number <= max && number >= min;
if (!valid) {
System.out.println(errorMessage);
}
} while (!valid);
return number;
}
//********************************************************************
public static Employee userInput()
{
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee ID:");
int employeeId = keyboard.nextInt();
temp = keyboard.nextLine();
System.out.println("Please enter the Employee E-mail address:");
String employeeEmail = keyboard.nextLine();
return e = new Employee(employeeName , employeeId, employeeEmail);
}
//********************************************************************
public static Employee userInputByName()
{
//String temp is for some reason needed. If it is not included
//The code will not execute properly.
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
return e = new Employee(employeeName);
}
//********************************************************************
public static Employee userInputByEmail()
{
//String temp is for some reason needed. If it is not included
//The code will not execute properly.
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Email:");
String employeeEmail = keyboard.nextLine();
//This can use the employeeName's constructor because java accepts the parameters instead
//of the name's.
return e = new Employee(employeeEmail);
}
//********************************************************************
}
SearchByEmail
public boolean searchByEmail(String employeeEmail)
{
//(for(Employee e : map.values()) {...})
//and check for each employee if his/her email matches the searched value
boolean employee = map.equals(employeeEmail);
System.out.println(employee);
return employee;
}
First of all,
map.equals(employeeEmail);
doesn't really make sense. map is a Hashmap, and employeeEmail is a String. Under what conditions would they be equal?
It is unclear what you store in the map and how, since you have neither included the declaration of the map, nor the code that inserts new values. I'll assume for now that you store mappings like name -> Employee. If you want to search for an employee based on an email address I suggest you do something like
Employee findByEmail(String email) {
for (Employee employee : yourMap.values())
if (employee.getEmail().equals(email))
return employee;
// Not found.
return null;
}
then to check if an employee with email exists, you could do
public boolean searchByEmail(String employeeEmail) {
boolean employee = findByEmail(employeeEmail) != null;
System.out.println(employee);
return employee;
}
I assume map is of type Map<S,T> for some S,T, and thus it is not of the same type as employeeEmail, and specifically it does not equals() it.
I suspect you are looking for Map.containsValue() (if the email is the value in the map) or Map.containsKey() (if the email is the key of the map), depending on what exactly map is mapping, if the mapping is to/from the string value.
EDIT: based on clarifications on comments:
Since the email is not a key nor value in map, the suggested solution won't work as it is. So you can chose one of those:
Use #aioobe's solution to iterate and check each email.
Add an extra field to the class: Map<String,Employee> map2 which will map: email_address->employee. Given this map, you can search for an email using map2.containsKey(email). It will ensure faster lookup for an employee from an email and the expanse of holding an extra map. I'd go with this choice if I were you.

Categories