Adding userInput to EmployeeStore - java

I made an EmployeeStore to obviously store employee details such as name,id and email. I set up a menu and now whenever the user wants to add an employee i get stuck on what to do.
Here is my code:
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 void userInput()
{
}
//********************************************************************
}
Add Method:
//Add to the Hashmap : Employee.
public void add(Employee employee)
{
map.put(employee.getEmployeeName(), employee);
}
//********************************************************************
MainApp:
//Imports.
import java.util.Scanner;
//********************************************************************
public class MainApp
{
//The Scanner is declared here for use throughout the whole MainApp.
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
//Create a Store named Store and add Employee's to the Store.
EmployeeStore Store = new EmployeeStore();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
//********************************************************************
/*Test Code.
Store.searchByName("James O' Carroll");
Store.print();
Store.searchByEmail("gmail.com");
Employee andy = Store.searchByEmail("hotmail.com");
System.out.println(andy);
Employee employee = Store.searchByName("James O' Carroll");
if (employee != null)
{
employee.setEmployeeName("Joe");
employee.setEmployeeId(1);
employee.setEmployeeEmail("webmail.com");
Store.edit(employee);
Store.print();
}*/
//********************************************************************
int choice ;
System.out.println("Welcome to the Company Database.");
do
{
choice = MenuMethods.getMenuChoice(
"1.\tView All" +
"\n2.\tAdd" +
"\n3.\tDelete" +
"\n4.\tDelete All " +
"\n5.\tEdit" +
"\n6.\tSearch" +
"\n7.\tPrint"+
"\n8.\tExit", 8, "Please enter your choice:", "Error [1,8] Only");
//String temp = keyboard.nextLine(); This prevented entering the choice.
switch (choice)
{
case 1:
System.out.println("View All");
Store.print();
break;
case 2:
System.out.println("Add");
//Store.add();
break;
case 3:
System.out.println("Delete");
//Store.delete();
break;
case 4:
System.out.println("Delete All");
Store.clear();
break;
case 5:
System.out.println("Edit");
break;
case 6:
System.out.println("Search");
Store.clear();
break;
case 7:
System.out.println("Print");
Store.print();
break;
case 8:
System.out.println("Exit");
break;
}
} while (choice != 8);
}
}

I think you're missing the next steps, before adding the employee. Ask to the user about the Employee name and email, and only after that, add it to your Store.

Related

ArrayList Collections error: which part of my code is wrong?

I would be required to write an array list of Mobile, do some operations such as add, remove, update and display. However, when it comes to sorting objects in arraylist, I am a little bit confused.
I am talking and referring to https://beginnersbook.com/2017/08/comparator-interface-in-java/
In drive class
//Create an arraylist of Mobile
ArrayList<Mobile> themobile = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Mobile");
System.out.println("Please select a number in the following: ");
while (true) {
//A list of options
System.out.println("1. Diplay the next mobile.");
System.out.println("2. Display the previous mobile.");
System.out.println("3. Add a new mobile.");
System.out.println("4. Remove a new mobile");
System.out.println("5. Update a mobile.");
System.out.println("0. Exit");
//prompt user input
int choice = input.nextInt();
switch(choice) {
case 1:
//displayNext(themobile);
break;
case 2:
//displayPrevious(themobile);
break;
case 3:
addMobile(themobile);
break;
case 4:
removeMobile(themobile);
break;
case 5:
updateMobile(themobile);
break;
case 0:
System.out.println("Thank you for using a Mobile arraylist");
System.exit(0);
}
}
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
}
In mobile class
public class Mobile implements Comparable<Mobile> {
private String brandName;
private int modelNumber;
private int internalMemoryS;
private int noOfAvailCameras;
public Mobile() {
}
public Mobile(String brandName, int modelNumber, int internalMemoryS, int noOfAvailCameras) {
this.brandName = brandName;
this.modelNumber = modelNumber;
this.internalMemoryS = internalMemoryS;
this.noOfAvailCameras = noOfAvailCameras;
}
public String getBrandName() {
return this.brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public int getModelNumber() {
return this.modelNumber;
}
public void setModelNumber(int modelNumber) {
this.modelNumber = modelNumber;
}
public int getInternalMemoryS() {
return internalMemoryS;
}
public void setInternalMemoryS(int internalMemoryS) {
this.internalMemoryS = internalMemoryS;
}
public int getNoOfAvailCameras() {
return noOfAvailCameras;
}
public void setNoOfAvailCameras(int noOfAvailCameras) {
this.noOfAvailCameras = noOfAvailCameras;
}
public int compareTo(Mobile m) {
return this.brandName.compareTo(m.getBrandName());
}
public String toString() {
return "Brand name: " + brandName + "Model number: " + modelNumber + "Internal memory space: " + internalMemoryS + "No of available cameras: " + noOfAvailCameras;
}
}
Each method has its own class & import java.util.*;
public class MobileByMoNum implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getModelNumber() - m2.getModelNumber();
}
}
public class MobileByBrandName implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getBrandName().compareTo(m2.getBrandName());
}
}
public class MobileByInS implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getInternalMemoryS() - m2.getInternalMemoryS();
}
}
Outcome:
TestMobile.java:48: error: unreachable statement
Collections.sort(themobile, new MobileByBrandName());
^
1 error
Any help and clarification is much appreciated. Thank you
As this code
while (true) {
never exits, the code below this loop is unreachable
Maybe System.exit(0); should maybe only be breaking the while loop.
Note break in a switch will not break the while loop
The code after while loop is never reached. You need to write some logic to break out of the while loop. One easy way to fix this is:
int choice = -1;
while (choice != 0) {
choice = input.nextInt();
switch (choice) {
//...other cases
case 0:
System.out.println("Thank you for using a Mobile arraylist");
}
}
Collections.sort(...);
System.out.println(...);
Put these lines inside while loop
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
Also you can simplify the operation of comparison by using Comparator.comparing available from java 8 onwards. Like:
Comparator<Mobile> comparator = Comparator.comparing(new Function<Mobile,
#Override
public String apply(Mobile t) {
return t.getBrandName();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getModelNumber();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getInternalMemoryS();
}
});
Collections.sort(themobile, comparator);

How do I create a switch-statement in my main class that when that case is selected will run another main class in my program?

I have multiple classes such as customer, customers, employee, employees, product, products. The programs with 's' are main classes. I have one Main class, I want this to be the start point of the program. I'd like a switch-statement in it. I'd like to ask user for input 1-3 and then run that main class from their input. Such as if input is 1 it will run the customers main, etc. How do I do this?
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InputValidationException {
//run customer add/edit/remove
int choice = 0;
while (true) {
displayMenu();
switch (choice) {
case 1:
customers.main(null);
break;
case 2:
cars.main(null);
break;
case 3:
Staff.main(null);
break;
}
}
}
private static void displayMenu() {
Scanner input;
{
input = new Scanner(System.in);
{
System.out.println("1. Customers");
System.out.println("2. Cars");
System.out.println("3. Staff");
System.out.println("Which would you like to add/edit: ");
String choice = input.nextLine();
}
}
}
}
My other classes are fairly similar to this:
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
//creates and array of the customers
public final class customers {
public static void main(String[] args) throws InputValidationException {
//add new customer
CopyOnWriteArrayList<customer> customers = new CopyOnWriteArrayList<>();
//List will fail in case of remove due to ConcurrentModificationException
//loop getting input
//input 'q' to quit
Scanner input;
{
//scanner to get the input
input = new Scanner(System.in);
{
while (true) {
//ask user for input and get input
System.out.println("Enter id (press 'q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//add to array list
customers.add(new customer(id, firstName, lastName));
}
}
}
//Display All
System.out.println("Current List: ");
for (customer customer : customers) {
System.out.println(customer.toString());
}
// search
System.out.println("Enter name to search and display");
String searchString = input.nextLine();
for (customer customer : customers) {
if (customer.search(searchString) != null) {
System.out.println(customer.toString());
}
}
//Remove
System.out.println("Enter name to search & remove");
searchString = input.nextLine();
for (customer customer : customers) {
if (customer.search(searchString) != null) {
System.out.println(customer.toString() + " is removed from the List");
customers.remove(customer);
}
}
}
}
The customer class just contains variables, setters, getters and constructors
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String input;
do {
input = displayMenu();
switch (input) {
case "1":
customers.main(args);
break;
case "2":
cars.main(args);
break;
case "3":
Staff.main(args);
break;
}
} while (!"exit".equals(input));
}
private static String displayMenu() {
Scanner input = new Scanner(System.in);
System.out.println("1. Customers");
System.out.println("2. Cars");
System.out.println("3. Staff");
System.out.println("Which would you like to add/edit: ");
return input.nextLine();
}
}
class customers {
public static void main(String[] args) {
System.out.println("hello from 'customers'!");
}
}
class cars {
public static void main(String[] args) {
System.out.println("hello from 'cars'");
}
}
class Staff {
public static void main(String[] args) {
System.out.println("hello from 'Staff'");
}
}
import java.util.Scanner;
public class MainClasss {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String option = scanner.next();
switch (option) {
case "1" :
AnotherMainClass.main(args);
break;
case "2" :
AnotherAnotherMainClass.main(args);
break;
default:
System.out.println("not found!");
}
}
}
class AnotherMainClass {
public static void main(String[] args) {
System.out.println("Hello from AnotherMainClass.main!");
}
}
class AnotherAnotherMainClass {
public static void main(String[] args) {
System.out.println("Hello from AnotherAnotherMainClass.main!");
}
}
input:
1
output:
Hello from AnotherMainClass.main!

How to add user input into an array

This is the parent class
public class Holding {
private String holdingId, title;
private int defaultLoanFee, maxLoanPeriod, calculateLateFee;
public Holding(String holdingId, String title){
this.holdingId = holdingId;
this.title = title;
}
public String getId(){
return this.holdingId;
}
public String getTitle(){
return this.title;
}
public int getDefaultLoanFee(){
return this.defaultLoanFee;
}
public int getMaxLoanPeriod(){
return this.maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the child class:
public class Book extends Holding{
private String holdingId, title;
private final int defaultLoanFee = 10;
private final int maxLoanPeriod = 28;
public Book(String holdingId, String title){
super(holdingId, title);
}
public String getHoldingId() {
return holdingId;
}
public String getTitle(){
return title;
}
public int getDefautLoanFee(){
return defaultLoanFee;
}
public int getMaxLoanPeriod(){
return maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getHoldingId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the menu:
public class LibraryMenu {
static Holding[]holding = new Holding[15];
static int hold = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int options = keyboard.nextInt();
do{
}
System.out.println();
System.out.println("Library Management System");
System.out.println("1. Add Holding");
System.out.println("2. Remove Holding");
switch(options){
case 1:
addHolding();
break;
default:
System.out.println("Please enter the following options");
}
}while(options == 13);
System.out.println("Thank you");
}
public static void addHolding(){
System.out.println("1. Book");
System.out.println("2. Video");
int input1 = input.nextInt();
switch(input1){
case 1:
addBook();
break;
case 2:
addVideo();
break;
default:
System.out.println("Please select the following options");
break;
}
}
public static void addBook(){
}
}
All i want is when a user wants to add a book, the user will type in the title and id for it and it will save into the array, and when it is done, it will go back to the menu. I cant seem to do it with my knowledge at the moment.
i tried to do this in the addBook() method
holding[hold] = new Book();
holding[hold].setBook();
the setBook method would be in the Book class, to complete the setBook, i have to make set methods for all the get method. But when i do this, the constructor is undefined.
public void setBook(){
System.out.println("Title: " + setTitle());
System.out.println("ID: " + setHoldingId());
System.out.println("Loan fee: " + setDefaultLoanFee());
System.out.println("Max Loan Period: " + setMaxLoanPeriod());
}
If there is anything wrong with my code, please feel free to say it to me :D
Thanks.
edit: After the user adds a book or video, when the user wants to print all the holdings, it will show the title, id, loan fee and max loan period. How do i do that?
edit2: Clean up a few parts that wasn't necessary with my question
I would suggest you to use "List of Object" concept in handling it.
1) You can define a List of Book object for example.
List<Book> bookList = new ArrayList<Book>();
2) Everytime when you hit AddBook() function, you can then do something like this.
//Create a temporary object of Book to get the user input data.
Book tempBook = new Book(holdingIDParam, titleParam);
//Add them to the list
bookList.Add(tempBook);
3) You can then use that list to your likings, whether to store them into a .txt based database or to use them throughout the program. Usage example:
bookList.get(theDesiredIndex).getBook() ...
I am not entirely sure of what you want but after paying focus on your bold text,this is what I can understand for your case. Feel free to correct me on your requirements if it doesn't meet.
Hope it helps :)

Why end-of-file indicator isn't working in NetBeans?

I am practicing a programming task given in my course literature. The program will keep asking the user to enter student's grades until they enter end-of-file indicator.
What is happening in my case is typing ctrl+Z (on windows, as it instructs me in book) doesn't work. It happens nothing afetr I doing this. Is it a problem with my console window or program?
GradeBook class:
package gradebook;
import java.util.Scanner;
public class GradeBook {
private String courseName;
private int totalGrade;
private int gradeCounter;
private int aCount;
private int bCount;
private int cCount;
private int dCount;
private int fCount;
//Create a contructor
public GradeBook(String name) {
courseName = name;
}
GradeBook() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setCourseName(String name) {
courseName = name;
}
public String getCourseName() {
return courseName;
}
public void displayMessage() {
System.out.printf("Welcome to the course\n%s!\n\n", getCourseName());
}
public void inputGrade() {
//int gradeEnteredByuser;
Scanner input = new Scanner(System.in);
int gradeEnteredByuser;
System.out.printf("%s\n%s\n %s\n %s\n", "Enter the integer grade in the range 0-100", "Type the end-of file indicator to terminate input:",
"On Unix/Linux/Mac OS X type <Ctrl> d then press enter", "On windows type <Ctrl> z then press enter:");
while (input.hasNext()) {
//int gradeEnteredByuser;
gradeEnteredByuser = input.nextInt();
totalGrade += gradeEnteredByuser;
gradeCounter++;
incrementLetterGradeCounter(gradeEnteredByuser);
}
}
private void incrementLetterGradeCounter(int gradeEnteredByuser) {
switch (gradeEnteredByuser / 10)
{
case 9:
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case 7:
++cCount;
break;
case 6:
++dCount;
default:
++fCount;
}
}
public void displayGradeReport(){
System.out.println("\nGrade report");
if(gradeCounter!=0){
double average=(double)totalGrade/gradeCounter;
System.out.printf("Total of the %d grades entered is %d\n", gradeCounter,totalGrade);
System.out.printf("Class avereage is %.2f\n", average);
System.out.printf("%s\n%s\n%s\n%s\n%s\n%s\n",
"Number of students who received each grade:",
"A: ", aCount,
"B: ", bCount,
"C: ", cCount,
"D: ", dCount,
"F: ", fCount);
}else{
System.out.println("No grade were entered:re");
}
}
}
GradeBookTest class:
package gradebook;
import java.util.Scanner;
public class GradeBookTest {
public static void main(String[] args) {
GradeBook gb=new GradeBook("Introduction to computer science");
gb.displayMessage();
gb.inputGrade();
gb.displayGradeReport();
// TODO code application logic here
}
}

Scanner Input not Reading Method Calling as a Parameter

First of All here's the Codes:
Product Information:
public class ProductInformation
{
public String code;
public String itemName;
public double price;
//Constructor
public ProductInformation()
{ itemName="-";
code="-";
price=0;}
//Setter
public void setItemName(String itemName)
{ this.itemName=itemName;}
public void setCode(String code)
{ this.code=code;}
public void setPrice(double price)
{ this.price=price;}
//Getter
public String getItemName()
{ return itemName;}
public double getPrice()
{ return price;}
public String getCode()
{ return code;}
//Products
public void getProduct(String code)
{ if(code == "A001"){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code == "A002"){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code == "A003"){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code == "A004"){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code == "A005"){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
}
import java.util.*;
Product Display:
public class ProductDisplay
{ public ProductInformation product;
public ProductDisplay()
{
System.out.println("\t\t\t\t RG COMPUTER SHOP");
System.out.println("\t\t\t\t Makati City");
System.out.println("\t\tP R O D U C T\tI N F O R M A T I O N");
System.out.println("-------------------------------------------------------");
System.out.println("\t\tCode\t\tDescription\t\tUnit Price");
System.out.println("-------------------------------------------------------");
product = new ProductInformation();
product.getProduct("A001");
display();
product = new ProductInformation();
product.getProduct("A002");
display();
product = new ProductInformation();
product.getProduct("A003");
display();
product = new ProductInformation();
product.getProduct("A004");
display();
product = new ProductInformation();
product.getProduct("A005");
display();
}
// Display Method
public void display()
{ System.out.println("\t\t" + product.getCode()
+ "\t\t" + product.getItemName()
+ "\t\t" + product.getPrice()); }
}
My Problem is here in PointOfSale
I tried to let the buyer decide by entering a Product Code
after entering the getProduct I get is always "A005" Even if I enter "A001" or something else. I think the product.getProduct(code) is not working out. Can someone help me fix this problem so i can continue scripting this
import java.util.*;
public class PointOfSale extends ProductDisplay
{
public PointOfSale()
{ System.out.print("\nPurchase Item(y/n)?");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
if("y".equalsIgnoreCase(line)){
OpenOrder();
}
}
//=============================================
public void OpenOrder() // New Order
{ ArrayList<String> ProductList = new ArrayList<String>();
ProductList.add("A001"); ProductList.add("A002");
ProductList.add("A003"); ProductList.add("A004");
ProductList.add("A005");
System.out.print("Select Product Code:");
Scanner sc = new Scanner(System.in);
String code = sc.next();
if(ProductList.contains(code))
{ product.getProduct(code);
display(); EnterQuantity(); }
else System.out.print("Product Code is Invalid\n"); System.exit(0);}
//==============================================
public void EnterQuantity() //Entering Quantity
{
try{
System.out.print("Enter Quantity:");
Scanner sc = new Scanner(System.in);
int quantity = sc.nextInt();
double amount = quantity * product.getPrice();
System.out.print("Amount: " + amount);}
catch (InputMismatchException nfe)
{System.out.print("\nInvalid Entry: Input must be a Number.\n"); System.exit(0);}
}
// Main Method
public static void main(String[] args)
{ new PointOfSale(); }
}
You are comparing strings for equality in your getProduct() method. Strings are objects, so you probably want to use the equals() method:
public void getProduct(String code)
{ if(code.equals("A001")){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code.equals("A002")){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code.equals("A003")){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code.equals("A004")){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code.equals("A005")){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
One major problem is that you're comparing Strings using == and you in general shouldn't do that as this compares if one object reference is the same as another and you don't care about this. Instead you care if the two String variables hold the same String representation, and for this use the equals() or equalsIgnoreCase() methods.

Categories