Variable cannot be resolved error in Java - java

I know this is a very very common error but I am stuck on this one and I totally don't understand why is it happening.
Here is a part of my code
import java.util.ArrayList;
import java.util.Scanner;
public class Manager {
private static Scanner sc = new Scanner(System.in);
protected static ArrayList<String> identifications = new ArrayList<String>();
protected static String[] signIn() {
System.out.println("Hi !");
System.out.println("Welcome to School Management System");
System.out.print("Please enter your ID number : ");
boolean idValid = false;
String providedID = null;
int idListPosition = -1;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
while (idValid != true) {
for (String element : identifications) {
if (element.equals(providedID)) {
idValid = true;
idListPosition = identifications.indexOf(element);
break;
}
}
if (idValid && idListPosition != -1) {
System.out.println("Welcome !");
String[] returnValue = {"true", identifications.get(idListPosition), identifications.get(idListPosition + 1), identifications.get(idListPosition + 2)};
return (returnValue);
} else {
System.out.println("Error : the ID you entered does not exist. Please try again");
providedID = null;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
}
}
}
public static void main(String[] args) {
init();
String[] response = signIn();
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}
protected static void init() {
identifications.add("056789");
identifications.add("teacher");
identifications.add("Temperson");
}
}
The Teacher and Student classes are empty for now. I just made them use the super constructor of their parent class Person :
public class Person {
String type;
String name;
String idNumber;
public Person(String idnumber, String newType, String providedName) {
this.idNumber = idnumber;
this.type = newType;
this.name = providedName;
}
protected String[] showInfos() {
String[] returnValue = {this.type, this.name, this.idNumber};
return returnValue;
}
}
But I get user cannot be resolved to a variable and user cannot be resolved error.
Normally the code that needs user will never run unless sign in has completed. And since sign in never ends before a correct ID is entered, the user variable will always be assigned to a a value.
Thanks for helping !

The scope of the user object is limited to the if condition, hence you are getting this error.
If Teacher and Student extends Person then you can try this piece of code:
public static void main(String[] args) {
init();
String[] response = signIn();
Person user = null;
if (response[2].equals("teacher")) {
user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}

You're having a Scope problem here:
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
Variables declared in a if block are local to that if block. You can see this in it's simplest form with an example like this:
if(true) {
String value = "Out of Scope";
}
System.out.println(value); //value cannot be seen outside the if block
You will need to declare your Teacher and/or Student variable outside the if block if you wish to use them after the block (this is where using your inheritance class would come in handy). Using the previous example:
boolean someCondition = true;
String value;
if(someCondition) {
value = "In Scope - True";
} else {
value = "In Scope - False";
}
System.out.println(value); //value can now be seen

You have declared 2 different versions of user, so the print statement can't know which you mean. Or it couldn't if it could see either, but since each is declared inside of its own block, the print doesn't see either of them.

Related

Java program not saving object to HashMap

Either my save_product function in my Repository.java class doesn't save correctly into the map product_repository or, maybe it does save, but I'm not outputting it correctly in my find_product function in my Repository.java class. I think I'm using the correct function to search for the value in the map, .get
I experimented with product_repository.keySet().iterator().forEachRemaining(System.out::println); but that's the first time I ever used that... also please forgive how I insert the keyinto the map product_repository in the create_new_product function in the Controller.java class. I'm new to java ...
Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
Product.java
package com.company;
public class Product {
private String product_name;
private String product_brand;
private int product_cost;
private int product_count;
private boolean product_availability;
public Product() {
}
public Product(String product_name, String product_brand,
int product_cost, int product_count, boolean product_availability) {
this.product_name = product_name;
this.product_brand = product_brand;
this.product_cost = product_cost;
this.product_count = product_count;
this.product_availability = product_availability;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_brand() {
return product_brand;
}
public void setProduct_brand(String product_brand) {
this.product_brand = product_brand;
}
public int getProduct_cost() {
return product_cost;
}
public void setProduct_cost(int product_cost) {
this.product_cost = product_cost;
}
public int getProduct_count() {
return product_count;
}
public void setProduct_count(int product_count) {
this.product_count = product_count;
}
public boolean isProduct_availability() {
return product_availability;
}
public void setProduct_availability(boolean product_availability) {
this.product_availability = product_availability;
}
}
Controller.java
package com.company;
import java.util.Scanner;
public class Controller {
private static Long key;
public static void create_new_product(){
Repository repository = new Repository();
//Supplier supplier = new Supplier();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
key = 0L;
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
key++;
repository.save_product(key, product);
}
public void search_product(){
Repository repository = new Repository();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
repository.find_product(id);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
repository.find_product(name);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
Repository.java
package com.company;
import java.util.HashMap;
import java.util.Map;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap){
try{
if (product_repository.containsValue(newProductMap)) {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
else {
product_repository.put(key, newProductMap);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public void find_product(Long key){
try {
if (product_repository.containsKey(key)) {
System.out.println(product_repository.get(key));
}
else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
// Overload
public void find_product(String name) {
try {
if (product_repository.containsValue(name)) {
System.out.println(product_repository.get(name));
product_repository.keySet().iterator().forEachRemaining(System.out::println);
}
else {
System.out.println("No matches were found for product name: " + name);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
}
You have to make Repository repository a field of your Controller class. You are currently throwing the repositories away after your methods create_new_product and search_product have executed. Therefore you need to remove the first line of each of these methods.
Another problem is inside your find_product(String name) method where your call product_repository.get(name) but name is a String and the get method expects an ID, i.e. a Long so this call will always return null.
As it was pointed out before the repository has to be made global. However, the entire code is a bit messy. You are searching for a product id but the id is not shown to you. It is like searching for database records but the ids are autogenerated. Good luck with that. So I would suggest to allow this program to enter the id as well. It makes much more sense if you want to search for the id.
Otherwise, if you are interested in only the value, id can be taken out.
Below you can find the modified code that works for all the methods.
//main stays the same
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
//controller is a bit changed. Added global repository and improved the search.
import java.util.Collection;
import java.util.Scanner;
public class Controller {
private static Long key;
Repository repository = new Repository();
public void create_new_product() {
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product id: ");
long id = Long.parseLong(scanner.nextLine());
product.setProductId(id);
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
repository.save_product(id, product);
}
public void search_product() {
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
Product product = repository.find_product(id);
try {
if (product.getProduct_count() > 0) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
} else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
Collection<Product> products = repository.find_products(name);
if (products.size() > 0) {
for (Product product : products) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} else {
System.out.println(" out of stock.");
}
} else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
//Added a new field to the Repository so you can also search by key.
import java.util.*;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap) {
try {
if (!product_repository.containsKey(key)) {
product_repository.put(key, newProductMap);
} else {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public Product find_product(final Long key) {
try {
if (product_repository.containsKey(key)) {
System.out.println("Found product: " + product_repository.get(key).getProduct_name());
return product_repository.get(key);
} else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
return null;
}
// Overload
public Collection<Product> find_products(final String name) {
Collection<Product> values = new ArrayList<>();
for (Map.Entry<Long, Product> productEntry : product_repository.entrySet()) {
if (productEntry.getValue().getProduct_name().equals(name)) {
System.out.println("matches were found for product name: " + name);
values.add(productEntry.getValue());
}
}
return values;
}
}

My java file unexpectedly prints two lines of code after a method is called. What is causing this?

My file works the way I want, except for one issue. After it runs prompt_log_out(), if I type n for no, my code does a System.out.print() of my get_temporary_user_credentials(). So the output looks like this:
Username: griffin.keyes
Password: alphabet soup
Hello, Zookeeper!
As zookeeper, you have access to all of the animals' information and their daily monitoring logs. This allows you to track their feeding habits, habitat conditions, and general welfare.
Would you like to log out? Please type "y" for Yes or "n" for No.
n
Username: Password: <---This is what I don't understand
Username: griffin.keyes
Password: alphabet soup
...
My desired output is the two lines below it that prompt for a username and password again. I feel like it may have something to do with my while(!logout) { statement, but I can't really think of why this might be the issue.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.security.MessageDigest;
public class Authentication{
public static User temporary_user = new User();
public static File admin_file = new File("admin.txt");
public static File veterinarian_file = new File("veterinarian.txt");
public static File zookeeper_file = new File("zookeeper.txt");
public static int attempt_counter = 0;
public static boolean successful_login = false;
public static Scanner user_input = new Scanner(System.in);
public static boolean log_out = false;
public static void main(String []args) throws Exception{
while (!log_out) {
start_login();
if (successful_login) {
prompt_log_out();
}
}
}
public static void start_login() throws Exception {
User[] all_users = create_users();
attempt_counter = 0;
successful_login = false;
while (attempt_counter < 3 && !successful_login) {
get_temporary_user_credentials(user_input);
for (User u : all_users) {
if (temporary_user.username.equals(u.username)) {
if (temporary_user.encrypted_password.equals(u.encrypted_password)) {
print_file(u.role);
successful_login = true;
break;
}
}
}
attempt_counter++;
}
if (attempt_counter == 3 && !successful_login) {
//user_input.close();
log_out = true;
System.out.println(); //prints out a blank line for easier readability
System.out.println("You have made too many unsuccessful attempts. The program will now exit.");
}
}
public static void prompt_log_out(){
System.out.println(); //prints out a blank line for easier readability
System.out.println("Would you like to log out? Please type \"y\" for Yes or \"n\" for No.");
if ("y".equals(user_input.next())) {
log_out = true;
}
}
public static void get_temporary_user_credentials(Scanner user_input) throws Exception{
System.out.print("Username: ");
temporary_user.username = user_input.nextLine();
System.out.print("Password: ");
temporary_user.encrypted_password = encrypt(user_input.nextLine());
}
public static void check_credentials() {
}
public static String encrypt(String original) throws Exception {
StringBuffer sb = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
public static User[] create_users() throws Exception{
User users[] = new User[6];
int index_counter = 0;
File credentials_file = new File("credentials.txt");
String pattern = "[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"";
Scanner file_reader = new Scanner(credentials_file);
while (file_reader.hasNextLine()) {
users[index_counter] = new User();
users[index_counter].username = file_reader.findInLine(pattern);
users[index_counter].encrypted_password = file_reader.findInLine(pattern);
users[index_counter].password = file_reader.findInLine(pattern);
users[index_counter].role = file_reader.findInLine(pattern);
if (file_reader.hasNextLine() == true) {
file_reader.nextLine();
}
index_counter++;
}
//file_reader.close();
return users;
}
public static void print_file(String role) throws Exception {
System.out.println(); //prints a blank line for easier readability.
if (role.equals("admin")) {
Scanner file_reader = new Scanner(admin_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
else if (role.equals("veterinarian")) {
Scanner file_reader = new Scanner(veterinarian_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
else {
Scanner file_reader = new Scanner(zookeeper_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
}
}
class User {
String username;
String password;
String encrypted_password;
String role;
}
Any help would be greatly appreciated.
You have this method using the same Scanner Object "user_input", by call next(). The linebreak is still in the scanner buffer. Then the while loop back to start_login() if 'n' is enter. The linebreak is then consumed by temporary_user.username = user_input.nextLine();
public static void prompt_log_out(){
System.out.println(); //prints out a blank line for easier readability
System.out.println("Would you like to log out? Please type \"y\" for Yes or \"n\" for No.");
if ("y".equals(user_input.next())) {
log_out = true;
}
// A quick and dirty fix
user_input.nextLine()
}
attempt_counter = 0;
successful_login = false;
while (attempt_counter < 3 && !successful_login) {
Check the above condition its always true based on your declarations

Issues Serializing an ArrayList object containing other ArrayList objects

So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks
public class PasswordKeeper{
private ArrayList<SuperUser> users;
private static Scanner keyboard = new Scanner(System.in);
public PasswordKeeper() {
users = new ArrayList();
}
public void login() {
try {
// reads in SuperUser arraylist
get();
} catch (EOFException a) {
System.out.println("You are the First User!");
} catch (IOException b) {
System.out.println(b);
} catch (ClassNotFoundException c) {
System.out.println(c);
}
boolean loopDisplay = true;
while (loopDisplay) {
existingUser = keyboard.next();
existingPass = keyboard.next();
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
//saves after method call is over
try {
System.out.println("Saving.");
save(users);
} catch (IOException e) {
System.out.println(e);
}
}
}
//This happens if there is a new user
if(answer == 2){
SuperUser tempNew = null;
boolean cont = true;
String newUser;
String pass;
while(cont){
newUser = keyboard.nextLine();
System.out.println();
//System.out.println(users.size());
tempNew = new SuperUser(newUser, pass);
if(passValid(pass) == true){
if(makeSure(tempNew) == true){
System.out.println("Login Created!");
tempNew = new SuperUser(newUser, pass);
//actually being added to the arraylist
users.add(tempNew);
cont = false;
}
}
}
//SuperUser.display method
tempNew.display();
try{
System.out.println("Saving.");
save(users);
}catch(IOException e){
System.out.println(e);
}
}
}
}
//makeSure and passValid methods
public boolean makeSure(SuperUser user){
if(users.contains(user)){
return false;
}
return true;
}
public boolean passValid(String pass){
boolean passes = false;
String upper = "(.*[A-Z].*)";
String lower = "(.*[a-z].*)";
String numbers = "(.*[0-9].*)";
String special = "(.*[,~,!,#,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";
if((pass.length()>15) || (pass.length() < 8)){
System.out.println("Entry must contain over 8 characters\n" +
"and less than 15.");
passes = false;
}if(!pass.matches(upper) || !pass.matches(lower)){
System.out.println("Entry must contain at least one uppercase and lowercase");
passes = false;
}if(!pass.matches(numbers)){
System.out.println("Password should contain atleast one number.");
passes = false;
}if(!pass.matches(special)){
System.out.println("Password should contain atleast one special character");
passes = false;
}else{
passes = true;
}
return passes;
//serializable methods
public void save(ArrayList<SuperUser> obj) throws IOException {
File file = new File("userInformation.dat");
FileOutputStream fileOut = new FileOutputStream(file, false);
BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
out.writeObject(obj);
out.close();
fileOut.close();
}
public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream("userInformation.dat");
BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
ObjectInputStream in = new ObjectInputStream(buffedInput);
users = (ArrayList<SuperUser>) in.readObject();
in.close();
fileIn.close();
return users;
}
public class SuperUser implements Serializable {
private String userName;
private String password;
private static Scanner keyboard = new Scanner(System.in);
private ArrayList<LoginInfo> info = new ArrayList();
public SuperUser(String name, String pass) {
userName = name;
password = pass;
}
public String getUser() {
return userName;
}
public void display() {
String next = keyboard.next();
//want to add data to LoginInfo arraylist
if (next.equalsIgnoreCase("add")) {
add();
} else if (next.equalsIgnoreCase("delete")) {
delete();
} else if (numberCheck(next)) {
int choice = (int) Integer.parseInt(next) - 1;
edit(choice);
//!!!! this: after doing this i lose whatever data i added
//to the LoginInfo arraylist, right after this the
//SuperUser arraylist gets saved. but the added data to
//loginInfo does not
} else if (next.equalsIgnoreCase("logout")) {
System.out.println(info.size());
}
}
public boolean numberCheck(String in) {
try {
Integer.parseInt(in);
} catch (NumberFormatException e) {
return false;
}
return true;
}
//method to add to the Arraylist
public void add() {
System.out.println("What is the website name?:");
String trash = keyboard.nextLine();
String webName = keyboard.nextLine();
System.out.println("The Username?:");
String webUsername = keyboard.nextLine();
System.out.println("The Password?:");
String webPass = keyboard.nextLine();
info.add(new LoginInfo(webUsername, webPass, webName));
System.out.println(info.size());
//method goes back to display
display();
}
}
}
Your problem is here
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
You create a temporary object which with the username and password.
Your 'users.contains()' method returns true because '.equals()' is based on the username, however the 'temp' object is a different instance to that in the list.
So when you call 'temp.display()' it is not calling on an object in the list, so no data changes will save.
You need to find the existing object from the list for that user. I would suggest that you swap your list for a map keyed on username.
You have a list named users. Once you created new SuperUser instance (temp), you are checking that it belongs to this list (users.contains(temp), which is false of course - from where it will occur there?). If it have belonged, the method display would be called, which in turn would add LoginInfo to that SuperUser (add() call), but I bet in reality it doesn't happened.
Also, I see where you read from users (check whether new SuperUser instances belong there), I see where you overwrite it (during desealization) but I don't see adding any instance to there, which makes me think that it is always empty.
Are you sure that SuperUser contains any LoginInfo in its array list?

I can't figure out how to print Hire and Fire from Stack

import java.util.*;
import java.util.Stack;
class Person {
private String name;
private String SS;
public Person(String N, String S) {
this.name = N;
this.SS = S;
}
}
class Manager {
Scanner keyboard = new Scanner(System.in);
private Queue<Person> app = new Queue<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
public void Apply() throws QueueException {
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
app.enqueue(apply);
}
public void hire() throws QueueException {
if (!app.isEmpty()) {
hire.push(app.dequeue());
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
fire.push(hire.pop());
} else {
System.out.println("Nobody to fire");
}
}
}
public class Management {
public static void main(String[] args) throws QueueException, StackException{
Scanner keyboard = new Scanner (System.in);
Manager user = new Manager();
boolean test = true;
while (test){
System.out.print("Press \n\t1 ACCEPT APPLICANT");
System.out.print("\t2 Hire \n\t3 Fire \n\t4 Quit:");
int action = keyboard.nextInt();
String space = keyboard.nextLine();
if (action == 1){
user.Apply();
}else if (action == 2){
user.hire();
}else if (action == 3){
user.fire();
} else if (action == 4){
System.exit(0);
}
else{
System.out.println("Please try again.");
}
}
}
}
I can't figure out how I can print out the name and ssn of the person I just hired or fired. I tried using peek, but it's not working. Basically, the whole program is about whether to accept and application, hire or fire. If I accept an application, it will prompt for the user to enter their name and ss, and if I press hire/fire it should print out the name and ss of that person.
Youre defining the queue wrong.
Its more like: Queue<Person> app = new LinkedList<Person>();
and you need a print method. Here's the Manager class. The print is called in the the Management Class, and if you define Manager user = new Manager(); you're surly going to be looked at funny.
Remove all the Throws. They are not defined and are not used....
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
class Manager
{
Scanner keyboard = new Scanner(System.in);
//private Stack<Person> app = new Stack<Person>();
private Stack<Person> hire = new Stack<Person>();
private Stack<Person> fire = new Stack<Person>();
Queue<Person> app = new LinkedList<Person>();
public void Apply()
{
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
//app.enqueue(apply);
app.add(apply);
}
public void hire()
{
if (!app.isEmpty())
{
hire.push(app.remove());
}
else
{
System.out.println("Nobody to hire.");
}
}
public void fire()
{
if (!hire.isEmpty())
{
fire.push(hire.pop());
}
else
{
System.out.println("Nobody to fire");
}
}
public void dump()
{
while(!app.isEmpty())
{
Person p = app.remove();
System.out.println(p.getName()+" "+ p.getSS());
}
}
}

Text User Interface, cannot get a method to work

I have an assignment to carry out using BlueJ where I am given a class called HW4CustomerList and I must create a Text-Based UI for it. The class I have to create is called CustomerTUI and contains a method called addCustomer which adds a new Customer object of mine to an ArrayList. This method in particular is what I am stuck with. The class specification says that I cannot take any parameters (i.e. a no-args method). In previous work we have used the BlueJ 'method box' to interact with objects and add them to ArrayLists, however I do not know if this can be used in this particular instance. Please find below my code so far for CustomerTUI and the code for the Customer class and HW4CustomerList class. Many thanks in advance.
CustomerTUI class:
import java.util.Scanner;
public class CustomerTUI
{
private HW4CustomerList customerList;
private Scanner myScanner;
public CustomerTUI()
{
customerList = new HW4CustomerList();
myScanner = new Scanner(System.in);
}
public void menu()
{
int command;
boolean running = true;
while(running)
{
displayMenu();
command = getCommand();
execute(command);
}
}
private void addCustomer()
{
customerList.addCustomer();
}
private void displayMenu()
{
System.out.println(" CustomerList program ");
System.out.println("=========================================");
System.out.println("|Add a customer to the list..........[1]|");
System.out.println("|Get number of customers.............[2]|");
System.out.println("|Remove a customer from the list.....[3]|");
System.out.println("|Show all customer details...........[4]|");
System.out.println("|Show a specific customers details...[5]|");
System.out.println("|Quit................................[6]|");
System.out.println("=========================================");
}
private void execute(int command)
{
if(command == 1)
{
addCustomer();
}
else if(command == 2)
{
getNumberOfCustomers();
}
else if(command == 3)
{
removeCustomer();
}
else if(command == 4)
{
showAllCustomers();
}
else if(command == 5)
{
showCustomer();
}
else if(command == 6)
{
quitCommand();
}
else
{
unknownCommand(command);
}
}
private int getCommand()
{
System.out.println("Enter the command of the function you wish to use: ");
int command = myScanner.nextInt();
return command;
}
private void getNumberOfCustomers()
{
if(customerList.getNumberOfCustomers() == 1)
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customer.");
}
else
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customers.");
}
}
private void quitCommand()
{
System.out.println("The program is now closing down...");
System.exit(0);
}
private void removeCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to remove: ");
accNo = myScanner.next();
if (customerList.removeCustomer(accNo) == true)
{
System.out.println("Customer with account number " + accNo + " was successfully removed.");
}
else
{
System.out.println("Customer with account number " + accNo + " was NOT successfully removed.");
System.out.println("Please try again.");
}
}
private void showAllCustomers()
{
customerList.getAllCustomers();
}
private void showCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to view: ");
accNo = myScanner.next();
if(customerList.getCustomer(accNo) == false)
{
System.out.println("Could not find customer with account number " + accNo + ".");
}
else
{
return;
}
}
private void unknownCommand(int command)
{
System.out.println("Command number " + command + " is not valid. Please try again.");
}
}
HW4CustomerList class:
import java.util.*;
public class HW4CustomerList
{
private ArrayList<Customer> customers;
public HW4CustomerList()
{
customers = new ArrayList<Customer>();
}
public void addCustomer(Customer customer)
{
customers.add(customer);
}
public int getNumberOfCustomers()
{
return customers.size();
}
public boolean getCustomer(String accountNumber)
{
for(Customer customer : customers)
{
if(accountNumber.equals(customer.getAccountNumber()))
{
customer.printCustomerDetails();
return true;
}
}
return false;
}
public void getAllCustomers()
{
for(Customer customer : customers)
{
customer.printCustomerDetails();
System.out.println("\n");
}
}
public boolean removeCustomer(String accountNumber)
{
int index = 0;
for (Customer customer: customers)
{
if (accountNumber.equals(customer.getAccountNumber()))
{
customers.remove(index);
return true;
}
index++;
}
return false;
}
}
I think all you need to do is create a new Customer object in your addCustomer() method. This would probably require getting additional details:
public void addCustomer()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter customer name: ");
String name = scanner.nextLine();
//any additional details
Customer customer = new Customer(name, otherParams);
customers.add(customer);
}
Hope that helps!

Categories