Search Method not working - java

Basically i have a hashmap and the search method is missing a keyboard.next which should allow the user to input the name they want to search for. There are no errors. The output does not allow an opportunity for the user to enter the name they want to search. The weird thing is i can use the userInput method and it works perfectly. Here is my code:
Store declaration
//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");
Employee employee = MenuMethods.userInput();
Store.add(employee);
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");
Employee employee2 = MenuMethods.userInput();
Store.searchByName(employee2.getEmployeeName());
if (employee2 != null)
{
employee2.setEmployeeName("Joe");
employee2.setEmployeeId(1);
employee2.setEmployeeEmail("webmail.com");
Store.edit(employee2);
Store.print();
}
break;
case 6:
System.out.println("Search");
Employee employee1 = MenuMethods.userInputByName();
Store.searchByName(employee1.getEmployeeName());
break;
case 7:
System.out.println("Print");
Store.print();
break;
case 8:
System.out.println("Exit");
break;
}
} while (choice != 8);
}
}
//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()
{
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee Name:");
return e = new Employee(employeeName);
}
//********************************************************************
}
Search Method in the mainApp
case 6:
System.out.println("Search");
Employee employee1 = MenuMethods.userInputByName();
Store.searchByName(employee1.getEmployeeName());
break;
The actual Search method.
public Employee searchByName(String employeeName)
{
Employee employee = map.get(employeeName);
System.out.println(employee);
return employee;
}
//********************************************************************
The userInputByName method. This is where the problem seems to lie.
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()
{
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee Name:");
return e = new Employee(employeeName);
}
//********************************************************************

Let me try my best.
First of all, why is there two println statements in your userInputByName()?
public static Employee userInputByName()
{
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee Name:"); //!???
return e = new Employee(employeeName);
}
Then, in the case 6, you just call the method searchByName and does not check if the search is successful or not. I suggest:
case 6:
System.out.println("Search");
Employee employee1 = MenuMethods.userInputByName();
Employee foundEmployee = Store.searchByName(employee1.getEmployeeName());
if (foundEmployee != null) {
System.out.println("Found employee!");
} else {
System.out.println("Not Found!");
}
break;

Related

I want to accept full name of manager in my organization java app...i tried using sc.nextLine(); but it is showing InputMisMatch error

Below is my code focus area is case 1 and case 2. please suggest some simple ways to accept full name considering I am a beginner:
package Tester;
import java.util.Scanner;
import com.app.org.Emp;
import com.app.org.Mgr;
import com.app.org.Worker;
public class TestOrganization {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many people you want to recruit");
Emp[] org = new Emp[sc.nextInt()]; //holder array ...its not a emp object...its array type of object
boolean exit = false;
int index = 0;
while(!exit) {
System.out.println("Options\n"+"1.Hire Manager\n"+"2.Hire Worker\n"+"3.Display information of all employees\n"
+ "4.Update Performance Bonus or Hourly Rate");
switch (sc.nextInt()) {
case 1:{
if(index<org.length && index>=0) {
System.out.println("Manager Details: id, name, deptId, basic, performBonus");
org[index++] = new Mgr(sc.nextInt(),sc.nextLine(),sc.next(),sc.nextDouble(),sc.nextInt());
}else {
System.out.println("Invalid!!! index");
}
break;
}
case 2:{
if(index<org.length && index>=0) {
System.out.println("Worker Details: id, name, deptId, basic, hw, hr");
org[index++] = new Worker(sc.nextInt(),sc.nextLine(),sc.next(),sc.nextDouble(),sc.nextDouble(),sc.nextDouble());
}else System.out.println("invalid!!! index");
break;
}
case 3:{
System.out.println("Employees Details");
for (Emp e : org) {
if(e!=null)
System.out.println(e);
}
}
input:
How many people you want to recruit
5
Options
1.Hire Manager
2.Hire Worker
3.Display information of all employees
4.Update Performance Bonus or Hourly Rate
1
Manager Details: id, name, deptId, basic, performBonus
101
samarth shukla
Mixing the nextInt/nextDouble/... with the nextLine from scanner is always a bad idea.
The nextInt/nextDouble/... leave an newline character back on the Stream, which means when nextLine is called, it only picks up the newline-character, which is probably not what you want
Aside from what I commented, you can try reading each input on a separated line, using Integer.parseInt(read.nextLine()) for integer and Double.parseDouble() for double.
read.nextLine() for regular string input
Actual and Formal argument lists differ in length constructor java.
Better to use nextLine() first and then the rest.
Example :-
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
Mgr obj = new Mgr(sc.nextLine(), sc.nextDouble(), sc.nextInt());
}
}
class Mgr{
public Mgr(String name, Double dNo, int id ){
System.out.println(id +" and "+ name +"dNo "+ dNo);
}
}
Accept input in some variables and pass them to the object constructor.
Check this for more deatils https://stackoverflow.com/a/13102066/7575841
package tester;
import java.util.Scanner;
import com.app.org.Employee;
import com.app.org.Manager;
import com.app.org.Worker;
public class TestOrganisation {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.print("What is the strength of organisation ? ");
Employee[] employees = new Employee[cin.nextInt()];
int count = 0;
boolean again = true;
do {
System.out.println("***** Welcome To Virtual Organization *****");
System.out.println("1. Hire Manager");
System.out.println("2. Hire Worker");
System.out.println("3. Display All");
System.out.println("4. Update Performance Bonus/Hourly Rate");
System.out.println("0. Wrap Up");
System.out.print("Enter option number : ");
switch(cin.nextInt() ) {
case 1:
if (count < employees.length) {
System.out.println("Hire a new manager.");
System.out.print("Enter Employee ID : ");
int id = cin.nextInt();
System.out.print("Enter Departemnt ID : ");
int deptID = cin.nextInt();
cin.nextLine();
System.out.print("Enter Name : ");
String name = cin.nextLine();
System.out.print("Enter Basic Salary : ");
double basic = cin.nextDouble();
System.out.print("Enter Performance Bonus : ");
double perfBonus = cin.nextDouble();
employees[count++] = new Manager(id, deptID, name, basic, perfBonus);
System.out.println("Manager Hired Successfully.\n");
}
else {
System.out.println("\nNo more vacancy available.\n");
}
break;
case 2:
if (count < employees.length) {
System.out.println("Hire a new worker.");
System.out.print("Enter Employee ID : ");
int id = cin.nextInt();
System.out.print("Enter Departemnt ID : ");
int deptID = cin.nextInt();
cin.nextLine();
System.out.print("Enter Name : ");
String name = cin.nextLine();
System.out.print("Enter Basic Salary : ");
double basic = cin.nextDouble();
System.out.print("Enter Hourly Rate : ");
double hourlyRate = cin.nextDouble();
System.out.print("Enter Hours Worked : ");
int hoursWorked = cin.nextInt();
employees[count++] = new Worker(id, deptID, name, basic, hourlyRate, hoursWorked);
System.out.println("Wroker Hired Successfully.\n");
}
else {
System.out.println("\nNo more vacancy available.\n");
}
break;
case 3:
if (count == 0) {
System.out.println("\nOnly Ghosts Work Here.\n");
}
else {
System.out.println("\nList of employees work in organization.");
for (Employee e: employees) {
if (e instanceof Worker) {
System.out.print(e);
System.out.println(", whose net salary is " + ((Worker)e).computeNetSalary());
}
else if (e instanceof Manager) {
System.out.print(e);
System.out.println(", whose net salary is " + ((Manager)e).computeNetSalary());
}
else {
System.out.println("Position is either empty or a ghost works here.");
}
}
System.out.println();
}
break;
case 4:
if (count == 0) {
System.out.println("\nOnly Ghosts Work Here.\n");
}
else {
System.out.print("Enter Employee ID : ");
int empID = cin.nextInt();
for (Employee e: employees) {
if (e != null) {
if(e.equals(empID)) {
if (e instanceof Worker) {
System.out.print("Enter new hourly rate : ");
double hourlyRate = cin.nextDouble();
((Worker) e).setHourlyRate(hourlyRate);
System.out.println("Hourly Rate Updated.\n");
}
else if (e instanceof Manager) {
System.out.print("Enter new performance bonus : ");
double prefBonus = cin.nextDouble();
((Manager) e).setPerfBonus(prefBonus);
System.out.println("Performance Bonus Updated.\n");
}
else {
System.out.printf("\nEmployee with %id is a ghost.\n", empID);
}
}
break;
}
}
}
break;
case 0:
again = false;
System.out.println("Good Bye. Have a nice day.");
break;
default:
System.out.println("Invalid Option. Please Try Again.");
}
} while(again);
cin.close();
}
}

I had error in Department constructor in if else in dept function

I had an error in the Department constructor in the if else statement in dept() method. How can I solve this?
I tried several tries by making the function abstract using different function name but it doesn't work.
class Book
import java.util.*;
class Book
{
int Book_id;
String Book_Name;
String Author_Name;
int pages;
float prices;
void getbook()
{
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Book ID");
Book_id=SC.nextInt();
System.out.println("Enter the Book Name");
Book_Name=SC.next();
System.out.println("Enter the Author Name");
Author_Name=SC.next();
System.out.println("Enter the pages");
pages=SC.nextInt();
System.out.println("Enter the prices");
prices=SC.nextFloat();
}
void display()
{
System.out.println("Book Id"+Book_id);
System.out.println("Book Name"+Book_Name);
System.out.println("Author Name"+Author_Name);
System.out.println("Pages"+pages);
System.out.println("Prices"+prices);
}
}
class Student
class Student extends Book
{
String Student_N;
int roll_no;
}
class Department
class Department extends Student
{
int choice;
String Dept_Code;
Department(int roll,String C)
{
System.out.println(""+C+""+roll_no);
}
void dept()
{
Scanner SC=new Scanner(System.in);
System.out.println("1.Civil Enginerring");
System.out.println("2.Computer Enginerring");
System.out.println("3.Information Tecnology");
System.out.println("4.Mechanical Engineering");
System.out.println("5.Electorics Enginerring");
System.out.println("6.Electrical Enginerring");
System.out.println("Enter the choice");
choice=SC.nextInt();
switch (choice)
{
case 1:
dept_data();
break;
case 2:
dept_data();
break;
case 3:
dept_data();
break;
case 4:
dept_data();
break;
case 5:
dept_data();
break;
case 6:
dept_data();
break;
}
}
void dept_data()
{
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Student Details");
System.out.println("Enter the Student Name");
SC.next();
System.out.println("Enter the Student Roll No");
SC.nextInt();
System.out.println("Enter the Book ID");
SC.nextInt();
System.out.println("Enter the Book Name");
SC.next();
}
int dept_del(String C)
{
Scanner SC=new Scanner(System.in);
if(C.compareTo("ci")==0||C.compareTo("CI")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("IT")==0||C.compareTo("it")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("CO")==0||C.compareTo("co")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("ME")==0||C.compareTo("me")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("EC")==0||C.compareTo("ec")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("EE")==0||C.compareTo("ee")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
}
}
class Project
class Project
{
public static void main(String[] args)
{
int i=1,flag=0;
Department A[]=new Department[100];
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Choice");
System.out.println("1.Add a Book\n2.Display the Book");
while(flag==0)
{
int choice=SC.nextInt();
switch (choice)
{
case 1 :
A[i].getbook();
i++;
case 2:
int n=i;
for(i=0;i<n;i++)
A[i].display();
case 3:
flag=1;
break;
default:
System.out.println("Wrong Choice");
}
}
}
}
The problem in your constructor is that it receives int roll, String C and does nothig with them and the instance vars int choice& String Dept_Codeare not defined after the constructor executes.
Maybe you wanted to do:
Department(int choice, String Dept_Code) {
this.choice = choice;
this.Dept_Code = Dept_Code;
System.out.println("" + Dept_Code + " - " + choice);
}
In the switch(choice) some breaks are missing after case 1 & 2 if you want to separate add a book fom display the book and from case 3:
switch(choice) {
case 1 :
A[i].getbook();
i++;
break;
case 2:
int n=i;
for(i=0;i<n;i++)
A[i].display();
break;
case 3:
flag=1;
break;
default:
System.out.println("Wrong Choice");
}
And in the other switch it makes no sense to create a switch if all the cases just execute the same dept_data()
code.
And as a suggestion it's better to always use the constant first when comparing to prevent from possible null pointers:
"ci".compareTo(C) is better than C.compareTo("ci") as the second option could throw a null pointer exception if C is undefined. Also, have a look at naming conventions: https://www.geeksforgeeks.org/java-naming-conventions/

Add, View, Update, and Delete Student Record using Array

i need help with my code. I am stuck at 2 (View student record), we only allowed to use arrays and not arraylist or linked list. Any advice and help will do.
Heres the instructions:
Write a menu driven program that performs the following:
1.Add record
- can add N students record into the list (ID num, name, course, year)
2.View record
- can view record by ID number, by course, by course and year
- or view all
3.Update record
- can edit/modify the records attribute excluding the ID
4.Delete
- can remove student record
Heres my code:
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args){
getMenu();
}
public static void getMenu( ){
Student[] stud = new Student[100];
Scanner sc = new Scanner(System.in);
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select){
case 1:
addStud(stud);
getMenu();
break;
case 2:
viewStud(stud);
getMenu();
break;
case 3:
break;
case 4:
break;
case 0:
break;
default:
}
}
public static void addStud(Student[] stud){
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
int i = 0;
do{
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
}while (addMore == 1 );
}
public static void viewStud(Student[] stud){
for(int x = 0; x < stud.length ; ++x){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() + "\n");
}
}
}
My Student Class:
public class Student {
private int numID, year;
private String userName, course;
public Student(int numID, int year, String userName, String course) {
this.numID = numID;
this.year = year;
this.userName = userName;
this.course = course;
}
public int getNumID() {
return numID;
}
public void setNumID(int numID) {
this.numID = numID;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Hello thank you SNJ,
I remove my getMenu method and put the code in the main instead.But I'm unable to set the Student array and i to static
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args) {
static Student[] stud = new Student[100];
static int i = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select) {
case 1:
addStud(stud);
break;
case 2:
viewStud(stud);
break;
case 3:
break;
case 4:
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(Student[] stud) {
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
} while (addMore == 1);
}
public static void viewStud(Student[] stud) {
for (Student element : stud) {
if (null != element) {
System.out.println("1. Student ID: " + element.getNumID());
System.out.println("2. Student Name: " + element.getUserName());
System.out.println("3. Student Course: " + element.getCourse());
System.out.println("4. Student Year: " + element.getYear() + "\n");
}
}
}
You are loosing student value in between method calls.If you make Student array and i as static, it will retain your values between method calls.
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args){
static Student[] stud = new Student[100];
static int i = 0;
public static void main(String[] args) {
getMenu();
}
public static void getMenu() {
Scanner sc = new Scanner(System.in);
while (true) {
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select) {
case 1:
addStud(stud);
break;
case 2:
viewStud(stud);
break;
case 3:
break;
case 4:
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(Student[] stud) {
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
} while (addMore == 1);
}
public static void viewStud(Student[] stud) {
for (Student element : stud) {
if (null != element) {
System.out.println("1. Student ID: " + element.getNumID());
System.out.println("2. Student Name: " + element.getUserName());
System.out.println("3. Student Course: " + element.getCourse());
System.out.println("4. Student Year: " + element.getYear() + "\n");
}
}
}

Professor gets a java.io.FileNotFoundException but I don't?

I had a project for my Java class where the user enters patients for a hospital then the program reads a file and the user can choose to amend their added patients to the file, print it out to the screen, or both. The program works perfectly in NetBeans for me but in the professor's comments, he says his compiler got a FileNotFoundException(Edit: It is actually a runtime error), even though I included the file in the package. When I emailed him, he only repeated that he received a FileNotFoundException.
Here is the code:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class xyzHospital {
static int numOfPat;
static Scanner input = new Scanner(System.in);
static String inp;
static ArrayList<Patient> p = new ArrayList<>();
public static void main(String[] args) throws IOException {
boolean done = false;
importPatients();
System.out.print("Add new patients to the report:\n");
while (done == false){
addPatient();
System.out.print("Are you done adding patients? (Y or N)\n");
inp = input.nextLine();
switch (inp.toLowerCase()){
case "y": done = true;
break;
case "n": done = false;
break;
default: System.out.print("You did not enter a valid character. The program will print results then exit.\n\n");
done = true;
break;
}
}
printAll();
}
static public void addPatient(){
numOfPat++;
Patient pat = new Patient();
p.add(pat);
pat.addInfo(numOfPat);
}
static public void printAll() throws IOException{
System.out.print("Do you want to output the report to the screen ('S'), to a file ('F'), or both('B')?\n");
inp = input.next();
PrintWriter writer = new PrintWriter("XYZHospitalExampleData-1.txt");
switch (inp.toLowerCase()){
case "s":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
for(int i = 0; i<numOfPat;i++){
p.get(i).print();
}
break;
case "f":
writer.print(""); //writes over file so there is no duplicate patients
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
}
break;
case "b":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
writer.print("");
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
p.get(i).print();
}
break;
}
}
//each patient from the file is added as a patient object
static public void importPatients() throws IOException{
try(Scanner read = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
while(read.hasNextLine()){ //one more line means that there is another patient to add
numOfPat++;
read.nextLine();
}
read.close();
try(Scanner r = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
for (int j=0; j < numOfPat; j++){
String line = r.nextLine();
Patient pat = new Patient();
p.add(pat);
String[] str = line.split("\\^"); //the delimiter ^ is used to separate information in the file
for (int i = 0; i < str.length; i++){
if(str[i].isEmpty()||str[i].matches("0")||str[i] == null){ //if str[i] is empty, that means that it will be skipped over
i++;
}
switch (i){
case 0: p.get(j).ID = Integer.parseInt(str[i]);
break;
case 1: p.get(j).nameLast = str[i];
break;
case 2: p.get(j).nameFirst = str[i];
break;
case 3: p.get(j).address = str[i];
break;
case 4: p.get(j).opAddr = str[i];
break;
case 5: p.get(j).city = str[i];
break;
case 6: p.get(j).state = str[i];
break;
case 7: p.get(j).zip = Integer.parseInt(str[i]);
break;
case 8: p.get(j).optZip = Integer.parseInt(str[i]);
break;
case 9: p.get(j).payDate = str[i];
break;
case 10: p.get(j).payment = Double.parseDouble(str[i]);
break;
case 11: p.get(j).owed = Double.parseDouble(str[i]);
break;
default: System.out.print("Error.\n");
break;
}
}
}
r.close();
}
}
}
}
Here is the patient class:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class Patient {
Scanner input = new Scanner(System.in);
String nameFirst, nameLast, address, opAddr,city, state, payDate;
int zip, optZip, ID;
double owed, payment;
public void print() {
System.out.printf("%-8s%-9s%-20s%-10s%-8s%-7s%-15s%-11.2f%-10.2f%n", nameLast, nameFirst, address, city, state, zip, payDate, owed, payment);
}
public void printToFile()throws IOException{
try (PrintWriter writer = new PrintWriter(new FileWriter("XYZHospitalExampleData-1.txt", true))) {
writer.write(ID + "^" + nameLast+ "^" + nameFirst + "^" + address + "^" + opAddr + "^" + city + "^" + state + "^" + zip + "^" + optZip + "^"+ payDate + "^" + payment + "^" + owed +"\n");
writer.close();
}
}
private void setName(){
System.out.print("Enter patient's first name.\n"); //user is asked for all information
nameFirst = input.nextLine(); //first three inputs use nextLine so it consumes the end of line character, so the address will be put in the string correctly.
System.out.print("Enter patient's last name.\n"); //if next() is used, the address is cut off at the first whitespace and the other elements of the address
nameLast = input.nextLine(); //are stored in the upcoming inputs.
if (nameFirst.isEmpty()||nameLast.isEmpty()){
System.out.print("You must enter the first and last name.\n");
setName();
}
}
public String getName(){
return nameFirst + " " + nameLast;
}
private void setAddr(){
System.out.print("Enter patient's address.\n");
address = input.nextLine();
if (address.isEmpty()){
System.out.print("You must enter the patients address.\n");
setAddr();
}
}
public String getAddr(){
return address;
}
private void setCity(){
System.out.print("Enter patient's home city.\n");
city = input.nextLine();
if(city.isEmpty()){
System.out.print("You must enter the patients city.\n");
setCity();
}
}
public String getCity(){
return city;
}
private void setState(){
System.out.print("Enter patient's state.\n");
state = input.nextLine();
if(state.isEmpty()){
System.out.print("You must enter the patients state.\n");
setState();
}
}
public String getState(){
return state;
}
private void setDate(){
System.out.print("Enter the payment date.\n");
payDate = input.next();
if(payDate.isEmpty()){
System.out.print("You must enter a payment date.\n");
setDate();
}
}
public String getDate(){
return payDate;
}
private void setZip(){
System.out.print("Enter patient's zipcode.\n");
try{
zip = input.nextInt();
}
catch(Exception e){
System.out.print("You must enter a valid 5-digit zipcode.\n");
input.next();
setZip(); //if it says that the setZip call will make the function loop infinitely, it is just a warning, it will not loop infinitely.
}
int length = String.valueOf(zip).length();
if(length != 5 && zip > 0){
System.out.print("You must enter a valid 5-digit zipcode.\n");
setZip();
}
}
public int getZip(){
return zip;
}
private void setOwed(){
System.out.print("Enter patient's due balance.\n");
try{
owed = input.nextDouble();
}
catch(Exception e){
System.out.print("Amount has to be a non-negative number.\n");
input.next();
setOwed();
}
int length = String.valueOf(owed).length();
if (owed <0 || length == 0){
System.out.print("Amount has to be a non-negative number.\n");
setOwed();
}
}
public double getOwed(){
return owed;
}
private void setPayment(){
System.out.print("Enter patient's payment amount.\n");
try{
payment = input.nextDouble();
}
catch(Exception e){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
input.next();
setPayment();
}
int length = String.valueOf(payment).length();
if(payment < 0 || length ==0 || payment > owed){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
setPayment();
}
}
public double getPayment(){
return payment;
}
private void setID(int Id){
ID = Id;
}
public int getID(){
return ID;
}
public void addInfo(int ID){
setID(ID);
setName();
setAddr();
setCity();
setState();
setZip();
setOwed();
setPayment();
setDate();
}
}
And here is the file XYZHospitalExampleData-1.txt:
12345^Jones^John^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/05/2015^250.0^25000.0
12346^Jones^Sara^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/20/2017^50.0^50000.0
12347^Doe^John^1235 XYZ Drive^null^Test City^IN^11234^0^01/05/2016^350.0^56799.0
12348^Doe^Sara^1235 XYZ Drive^null^Test City^IN^11234^0^11/09/2017^100.0^5020.52
12349^Lawson^Lonnie^12 South Drive^null^Test City^IN^11236^0^03/15/2013^253.51^25065.52
12349^Anderson^Sara^156 North Avenue^null^Test City^IN^11246^0^05/05/2013^21.33^251.56
12350^Smith^Andy^2455 East Street^null^Test City^IN^11246^0^12/05/2017^365.21^2543.33
It starts with their ID and ends with the amount that they owe. Any help to understand why my professor's compiler is giving him an error would be appreciated, and what I can do to be sure that it will be able to find the file so I do not have this problem again.
In the beginning of your main method you call importPatients which reads data from the XYZHospitalExampleData-1.txt file. If this file is not present, you'll get an exception (in the runtime, not a compiler error).
Most probably something went wrong when your package was unpackaged. Maybe the file was not copied to the expected location, something like that. One of the ways to address this would be to catch the FileNotFoundException and to display a message describing what went wrong and what is expected.

Creating a Basic Java phone book

I'm just learning Java and trying to make a simple phone book. For this part I'm trying to prompt the user to choose one of the 3 options below.
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n': enterNumber;
system.out.println();
case 's':showNumber;
system.out.println();
case 'c': closeBook;
break;
default: System.out.println("Invalid Entry");
}
}
}
}
When I compile it i get errors on lines 37, 39, and 41 saying "Error: not a statement". I feel like something is missing. If anyone can help it would be greatly appreciated.
I am assuming that with the following lines you want to achieve to print the letter n for enterNumber in the console?
case 'n': enterNumber;
system.out.println();
This is not correct Java syntax. You will have to pass the variable value to the System.out.println method call:
case 'n': System.out.println(enterNumber);
Also note that Java is case sensitive, so you have to spell System with a capital letter.
On a side note, you will want to break; after each of your case statements, otherwise the code of the following cases will be executed as well:
switch (choice) {
case 'n': System.out.println(enterNumber);
break;
case 's': System.out.println(showNumber);
break;
case 'c': System.out.println(closeBook);
break;
default: System.out.println("Invalid Entry");
}
you do not have to write variable after 'cast' statement.
Refer below code.
import java.util.Scanner;
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n':
System.out.println();
case 's':
System.out.println();
case 'c':
break;
default: System.out.println("Invalid Entry");
}
}
}
}
I have made a special answer for you. I don't add additional explanation. It's a large answer. I tell more than you ask, but I've done my best to make a readable code, so that you can analyse step-by-step to understand what you need at least when trying to make a Phone Book (console test drive application). If you need more explanation, write under comments.
First make a PhoneEntry class:
import java.util.Objects;
public class PhoneEntry implements Comparable<PhoneEntry> {
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5Ba-zA-Z%5D%7B2%2C%7D((-%7C%5Cs)%5Ba-zA-Z%5D%7B2%2C%7D)*%24
private static final String NAME_PATTERN = "^[a-zA-Z]{2,}((\\-|\\s)[a-zA-Z]{2,})*$";
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5C%2B%3F%5Cd%2B((%5Cs%7C%5C-)%3F%5Cd%2B)%2B%24
private static final String NUMBER_PATTERN = "^\\+?\\d+((\\s|\\-)?\\d+)+$"; //^\+?\d+((\s|\-)?\d+)+$
private final String name;
private final String number;
public PhoneEntry(String name, String number) {
if (!name.matches(NAME_PATTERN) || !number.matches(NUMBER_PATTERN)) {
throw new IllegalArgumentException();
}
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public boolean nameContainsIgnoreCase(String keyword) {
return (keyword != null)
? name.toLowerCase().contains(keyword.toLowerCase())
: true;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof PhoneEntry)) {
return false;
}
PhoneEntry phoneEntry = (PhoneEntry) obj;
return name.equalsIgnoreCase(phoneEntry.name)
&& number.equalsIgnoreCase(phoneEntry.number);
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + Objects.hashCode(this.name.toLowerCase());
hash = 17 * hash + Objects.hashCode(this.number.toLowerCase());
return hash;
}
#Override
public int compareTo(PhoneEntry phoneEntry) {
return name.compareToIgnoreCase(phoneEntry.name);
}
}
Then the test drive
public class TestDrive {
private static final String choices = "nspc";
enum Choice {
CREATE, READ, PRINT, CLOSE;
static Choice getChoice(char c) {
switch (c) {
case 'n':
return Choice.CREATE;
case 's':
return Choice.READ;
case 'p':
return Choice.PRINT;
case 'c':
return Choice.CLOSE;
}
return null;
}
}
// Main
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
final Set<PhoneEntry> entries = new TreeSet<>();
Choice choice;
while ((choice = getChoice(kbd)) != Choice.CLOSE) {
switch (choice) {
case CREATE:
PhoneEntry entry = getPhoneEntry(kbd);
if (entry != null) {
entries.add(entry);
}
break;
case READ:
print(readEntries(entries, kbd));
break;
case PRINT:
print(entries);
break;
}
}
}
private static Choice getChoice(Scanner kbd) {
System.out.println("\nPlease select from the following");
System.out.println("\tn to Enter the number");
System.out.println("\ts to Show numbers by keyword ");
System.out.println("\tp to Show all numbers ");
System.out.println("\tc to Close the Phone book");
System.out.print("> ");
String input = kbd.nextLine();
Choice choice = null;
if (!input.isEmpty()
&& choices.contains(input.toLowerCase())
&& ((choice = Choice.getChoice(input.toLowerCase().charAt(0))) != null)) {
return choice;
}
System.out.println("ERR: INVALID ENTRY. TRY AGAIN");
return getChoice(kbd);
}
private static PhoneEntry getPhoneEntry(Scanner kbd) {
System.out.print("Type contact name: ");
String name = kbd.nextLine();
System.out.print("Type phone number: ");
String number = kbd.nextLine();
try {
return new PhoneEntry(name, number);
} catch (IllegalArgumentException ex) {
System.out.println("\nERR: WRONG ENTRY");
}
return null;
}
private static void print(Set<PhoneEntry> entries) {
System.out.println("\nPHONE NUMBERS\n");
entries.stream().forEach(entry -> {
System.out.printf("Name: %s%nPhone: %s%n%n",
entry.getName(), entry.getNumber());
});
}
private static Set<PhoneEntry> readEntries(Set<PhoneEntry> entries, Scanner kbd) {
System.out.print("Type keyword: ");
return entries.stream().filter(entry
-> entry.nameContainsIgnoreCase(kbd.nextLine()))
.collect(Collectors.toCollection(TreeSet::new));
}
}
Instead of enterNumber;, you have to write enterNumber();.
The parentheses mean: Call the method.

Categories

Resources