I finished this program and demo for my TA. I completely forgot one thing. So, the program is about hiring and firing people using stack and queues. I figured everything out except for one thing. I have to hire at least 3 people and whoever the first applicant is, I will hire them first so on. Here's the problem:
When I fire someone (The last person hired), that person should be the next person to get hired. Example:
Fired Name: b SS: 2
next person hired should be
Hired Name: b SS: 2.
I can't figure out how to get the last person fired to be the next person hired. Here's my program:
class Person {
public String name;
public 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>();
public Stack<Person> hire = new Stack<Person>();
public 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()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = app.dequeue();
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
Person newFire = fire.push(hire.pop());
System.out.println("Fired \nName: " + newFire.name + " SS: " + newFire.SS);
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("\n\t2 Hire \n\t3 Fire \n\t4 Quit:");
System.out.print("\nAnswer: \n");
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.");
}
}
you have this error on the hire() method.
Person newFire = app.dequeue();
you see that you are executing this line even tho app queue is Empty. just use fire stack instead of app queue.
public void hire() throws QueueException {
if (!app.isEmpty()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = fire.pop();
hire.push(newFire);
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}
Related
I am trying to write a small code in java .
I am getting error from method getTotalCost().
can you please check my code and point out what mistake i am doing.
I am creating a class Hamburger .
passing 3 variables to consutuctor.
then its my choice to add tomato or spinach to my Burger.
In my getTotalCost() i am trying to print value if myLettuce.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.amitsuneja.Lettuce.getCostOfLettuce()" because "this.myLettuce" is null at com.amitsuneja.Hamburger.getTotalCost(Hamburger.java:77) at com.amitsuneja.Main.main(Main.java:8)
Here is my Hamburger.java
public class Hamburger {
private String breadType;
private boolean isMeat;
private double priceOfBurger;
private Lettuce myLettuce;
private boolean addLettuce;
private Tomato myTomato;
private boolean addTomato;
private Carrot myCarrot;
private boolean addCarrot;
private Spinach mySpinach;
private boolean addSpinach;
private double toalCost;
Scanner myScanner = new Scanner(System.in);
public Hamburger(String breadType, boolean isMeat, double priceOfBurger) {
this.breadType = breadType;
this.isMeat = isMeat;
this.priceOfBurger = priceOfBurger;
System.out.println("Current cost of burger is: " + this.priceOfBurger);
System.out.println(" Would like to add some Lettuce?");
addLettuce = myScanner.nextBoolean();
if (addLettuce){
Lettuce myLettuce1 = new Lettuce(true);
}else{
Lettuce myLettuce1 = new Lettuce(false);
System.out.println("I am in Lettuce: " + myLettuce.getCostOfLettuce() + myLettuce.isHaveLettuce());
}
myScanner.nextLine();
System.out.println(" Would like to add some Tomato?");
addTomato = myScanner.nextBoolean();
if (addTomato){
Tomato myTomato = new Tomato(true);
}else{
Tomato myTomato = new Tomato(false);
}
myScanner.nextLine();
System.out.println(" Would like to add some carrot?");
addCarrot = myScanner.nextBoolean();
if (addCarrot){
Carrot myCarrot = new Carrot(true);
}else{
Carrot myCarrot = new Carrot(false);
}
myScanner.nextLine();
System.out.println(" Would like to add some Spinach?");
addSpinach = myScanner.nextBoolean();
if (addSpinach){
Spinach mySpinach = new Spinach(true);
}else{
Spinach mySpinach = new Spinach(false);
}
myScanner.nextLine();
myScanner.close();
}
public double getPriceOfBurger() {
return priceOfBurger;
}
public void getTotalCost(){
System.out.println("I am Here....................price = " + priceOfBurger);
System.out.println("I am in Lettuce: " + myLettuce.getCostOfLettuce() + myLettuce.isHaveLettuce());
}
Here is my Lettuce Class
package com.amitsuneja;
public class Lettuce {
private boolean haveLettuce;
private double costOfLettuce;
public Lettuce(boolean haveLettuce) {
this.haveLettuce = haveLettuce;
this.costOfLettuce =2d;
}
public boolean isHaveLettuce() {
return haveLettuce;
}
public void setHaveLettuce(boolean haveLettuce) {
this.haveLettuce = haveLettuce;
}
public double getCostOfLettuce() {
return costOfLettuce;
}
public void setCostOfLettuce(double costOfLettuce) {
this.costOfLettuce = costOfLettuce;
}
}
Change this code
if (addLettuce){
Lettuce myLettuce1 = new Lettuce(true);
}else{
Lettuce myLettuce1 = new Lettuce(false);
System.out.println("I am in Lettuce: " + myLettuce.getCostOfLettuce() + myLettuce.isHaveLettuce());
}
to -
if (addLettuce){
myLettuce = new Lettuce(true);
}else{
myLettuce = new Lettuce(false);
System.out.println("I am in Lettuce: " + myLettuce.getCostOfLettuce() + myLettuce.isHaveLettuce());
}
My Java code is a simple CRM using user input to detail a lead's information. But that's not important. My trouble here is I'm trying to write the objects in my ArrayList<> into a .txt file.
I have the method to write the objects done but this line of code:
case "20" : {
saveCustomerToFile(leadfilepath,);
break;
}
The error says expression is expected but I don't exactly know what to put there.
Here's my code:
Main Class:
public class Main {
private static int leadsId = 0;
private static int interactionId = 0;
private static LeadsManager leadsManager = new LeadsManager();
private static InteractionsManager interactionsManager = new InteractionsManager();
public static void main(String[] args) {
String leadfilepath = "leads.txt";
//Declare Scanner
Scanner input = new Scanner(System.in);
System.out.print("[MENU] \n"
+ "===[MANAGING LEADS]=== \n"
+ "1) View all Leads \n"
+ "2) Create new Leads \n"
+ "3) Update a lead \n"
+ "4) Delete a lead \n"
+ "===[MANAGING INTERACTIONS]=== \n"
+ "5) View all Interactions \n"
+ "6) Create new Interactions \n"
+ "7) Update an Interaction \n"
+ "8) Delete an Interaction \n"
+ "===[Reporting and Statistics]===\n"
+ "10) N/A\n"
+ "11) N/A\n"
+ "12) N/A\n"
+ "===[Save Progress]===\n"
+ "20) Save leads arrays data into file.\n"
+ "Please input the desired function:");
while(true){
String answer = input.nextLine();
switch (answer){
case "1" : {
printLeads();
break;
}
case "2" : {
LeadMethod();
break;
}
case "3": {
String leadId = enterLeadIdPrompt();
updateLeads(leadId);
break;
}
case "4" : {
String leadId = enterLeadIdPrompt();
deleteLeads(leadId);
break;
}
case "5" : {
System.out.println("Printing all the sales people in the list ...");
System.out.println(" ");
printAllInteractions();
break;
}
case "6" : {
addInteractionInfo();
break;
}
case "7" : {
String interactionId = enterInteractionIdPrompt();
updateInteractionInfo(interactionId);
break;
}
case "8" : {
String interactionId = enterInteractionIdPrompt();
deleteInteractionInfo(interactionId);
break;
}
case "20" : {
saveCustomerToFile(leadfilepath,);
break;
}
}
}
}
///////////////////////Methods for Lead///////////////////////////////////
////Main method for creating leads/////
public static void LeadMethod(){
Leads leads = createLeadsObject();
if(leadsManager.addLeads(leads)){
System.out.println("Added Lead Successfully! \n" + leads);
}
else{
System.out.println("Adding Lead failed!");
}
}
public static void saveCustomerToFile(Leads lead, String leadfilepath){
try{
FileWriter leadfw = new FileWriter(leadfilepath, true);
BufferedWriter leadbw = new BufferedWriter(leadfw);
PrintWriter leadpw = new PrintWriter(leadbw);
leadpw.println(lead.toString());
leadpw.flush();
leadpw.close();
JOptionPane.showMessageDialog(null, "Leads saved!");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Leads not saved!");
}
}
/////Creating the Lead Object from the Class and User input////////
private static Leads createLeadsObject(){
Scanner leadsInfoInput = new Scanner(System.in);
Leads leads = new Leads();
System.out.println("Enter Leads Data:");
leads.setLead_id(String.format("lead_%03d", leadsId++));
System.out.print("Name: ");
String Name = leadsInfoInput.nextLine();
leads.setName(Name);
System.out.print("Date of Birth (MM/DD/YYYY) : ");
String DateOfBirth = leadsInfoInput.nextLine();
leads.setDoB(DateOfBirth);
System.out.print("Gender (Male - 0, Female - 1) : ");
String Gender = leadsInfoInput.nextLine();
leads.setGender(Gender);
System.out.print("Phone Number : ");
String PhoneNumber = leadsInfoInput.nextLine();
leads.setPhone(PhoneNumber);
System.out.print("Email : ");
String Email = leadsInfoInput.nextLine();
leads.setEmail(Email);
System.out.print("Address : ");
String Address = leadsInfoInput.nextLine();
leads.setAddress(Address);
return leads;
}
////Printing out the leads on the console/////
private static void printLeads() { leadsManager.printAllLeads(); }
////Deleting a lead by ID////
private static void deleteLeads(String lead_id){
boolean isDeleted = leadsManager.deleteLeads(lead_id);
if(isDeleted){System.out.println("Deleting lead from the list...");
System.out.println("Deleted " + lead_id + " successfully!");
}else{
System.out.println("Delete lead failed!");
}
}
////Method to enter desired Lead ID////
private static String enterLeadIdPrompt(){
System.out.print("Enter customer id : ");
Scanner del = new Scanner(System.in);
return del.nextLine();
}
/////Method for updating a lead's data///////
private static void updateLeads(String lead_id) {
boolean isUpdated = leadsManager.updateLeads(lead_id);
if(isUpdated){
System.out.println("Update customer successful!");
}else{
System.out.println("Update customer failed.");
}
}
/////////////////////////////////////////////////////////////////
//////////////////////Interactions Section///////////////////////
///Method to call for adding Interaction
private static void addInteractionInfo() {
Interactions interaction = createInteractionObject();
boolean isAdded = interactionsManager.addInteraction(interaction);
if(isAdded){
System.out.println("Interaction added successfully!\n" + interaction);
}else{
System.out.println("Interaction add failed !");
}
}
////Method for Asking the Interaction's ID////
private static String enterInteractionIdPrompt(){
System.out.print("Enter model.Interaction Id : ");
Scanner interactionIdInput = new Scanner(System.in);
return interactionIdInput.nextLine();
}
//////Method to call for deleting an Interaction
private static void deleteInteractionInfo(String interactionId) {
boolean isDeleted = interactionsManager.deleteInteraction(interactionId);
if(isDeleted){
System.out.println("Delete interaction information successful!");
}else{
System.out.println("Delete interaction information failed.");
}
}
////Method to call for Updating Interaction's data
private static void updateInteractionInfo(String interactionId) {
boolean isUpdated = interactionsManager.updateInteraction(interactionId);
if(isUpdated){
System.out.println("Update interaction information successful!");
}else{
System.out.println("Update interaction information failed.");
}
}
///Method to call for printing interactions///
private static void printAllInteractions() {
interactionsManager.printAllInteractions();
}
/////User Input to create data for the Interaction object
private static Interactions createInteractionObject(){
Scanner interactionInfoInput = new Scanner(System.in);
Interactions interaction = new Interactions();
interaction.setInter_id(String.format("inter_%03d", interactionId++));
System.out.print("Date of interaction (MM/DD//YYYY) : ");
String dateOfInteraction = interactionInfoInput.nextLine();
interaction.setDoI(dateOfInteraction);
System.out.print("Lead ID : ");
String leadId = interactionInfoInput.nextLine();
Leads lead = leadsManager.getLeadsById(leadId);
if(lead == null){
while(lead == null){
System.out.println("Wrong customer id, please try again!");
leadId = interactionInfoInput.nextLine();
lead = leadsManager.getLeadsById(leadId);
}
}
interaction.setLead_id(lead);
System.out.print("Interaction Method (SNS / email / telephone / face to face) : ");
String method = interactionInfoInput.nextLine();
interaction.setMeans(method);
System.out.print("Potential (P - positive, NEG - negative, NEU - neutral) : ");
String potential = interactionInfoInput.nextLine();
interaction.setPotential(potential);
return interaction;
}
}
My Leads class:
public class Leads {
private String lead_id;
private String Name;
private String DoB;
private String Gender;
private String Phone;
private String Email;
private String Address;
//The Lead constructor
public Leads(String lead_id, String Name, String DoB, String Gender, String Phone, String Email, String Address){
this.lead_id = lead_id;
this.Name = Name;
this.DoB = DoB;
this.Gender = Gender;
this.Phone = Phone;
this.Email = Email;
this.Address = Address;
}
public Leads() {
}
///Mutators and Accessors////
public String getLead_id() {
return lead_id;
}
public void setLead_id(String lead_id) {
this.lead_id = lead_id;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public String getDoB(){
return DoB;
}
public void setDoB(String DoB){
this.DoB = DoB;
}
public String getGender(){
return Gender;
}
public void setGender(String Gender){
this.Gender = Gender;
}
public String getPhone(){
return Phone;
}
public void setPhone(String Phone){
this.Phone = Phone;
}
public String getEmail(){
return Email;
}
public void setEmail(String Email){
this.Email = Email;
}
public String getAddress(){
return Address;
}
public void setAddress (String Address){
this.Address = Address;
}
#Override
public String toString() {
return "ID: "+lead_id + ", Name: " + Name +", DOB: " + DoB + ", Gender: " + Gender + ", Phone
Number: " + Phone + ", Email: " + Email + ", Address: " + Address;
}
}
And my LeadsManager class:
private ArrayList<Leads> leads = new ArrayList<>();
public ArrayList<Leads> getLeads(){
return leads;
}
///Actual method to call a Lead from its ID/////
public Leads getLeadsById(String lead_id){
for (int i = 0; i < leads.size(); i++){
if(lead_id.equals(leads.get(i).getLead_id())){
return leads.get(i);
}
}
return null;
}
///Adding a lead////
public boolean addLeads(Leads lead){
return leads.add(lead);
}
////Actual printing////
public void printAllLeads(){
for (int i = 0; i < leads.size(); i++) {
System.out.println(leads.get(i));
}
if(leads.size()==0){
System.out.println("The list is empty.");
}
}
///Actual deleting////
public boolean deleteLeads(String lead_id){
Leads lead = getLeadsById(lead_id);
if(lead == null){
return false;
}else{
return leads.remove(lead);
}
}
////////Updating Data//////
/////Might not work!!! Duan check xem co dung dc khong. Xong thi xoa line note nay/////
public boolean updateLeads(String lead_Id){
Leads leads = getLeadsById(lead_Id);
if(leads == null){
return false;
}
printLeadUpdateManual();
Scanner s = new Scanner(System.in);
boolean isDone = false;
String newInfo = "";
Interactions inter = null;
while(!isDone){
String target = s.nextLine();
switch (target){
case "name" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validateName(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setName(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "dob" : {
System.out.print("enter new date of birth(MM/DD/YYYY) : ");
String newDate = new Scanner(System.in).nextLine();
boolean isValid = InputValidator.getInstance().validateBirthDay(newDate);
if(isValid){
leads.setDoB(newDate);
}else{
System.out.println("Invalid birthday form!");
}
break;
}
case "gender" : {
newInfo = updateInfoPrompt(target);
// leads.setGender(newInfo);
boolean isValid = InputValidator.getInstance().validateGender(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setGender(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "phone" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validatePhoneNumber(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setPhone(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "email" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validateEmail(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setEmail(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "address" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validateAddress(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setAddress(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "0" : {
isDone = true;
break;
}
default : {
System.out.println("Wrong Input !");
printLeadUpdateManual();
break;
}
}
}
return true;
}
private void printLeadUpdateManual(){
System.out.println("Which information would you like to update?");
System.out.println("OPTIONS : [name, dob (MM/DD/YYYY), gender, phone, email, address]");
System.out.println("Enter '0' when update is complete.");
}
private String updateInfoPrompt(String updateTarget){
System.out.println("Type new "+ updateTarget+" to update: ");
return new Scanner(System.in).nextLine();
}
in the beginning of your 'saveCustomerToFile' function we can see it is expecting two objects: a 'Leads' object and a 'String' object:
public static void saveCustomerToFile(Leads lead, String leadfilepath){
yet in your switch function you only send it one, in the 'Leads' object place and a comma:
case "20" : {
saveCustomerToFile(leadfilepath,);
you need to specify add a lead object and place the objects in the correct order the function expects for the program to work properly.
something like this:
case "20" : {
saveCustomerToFile(lead_object, leadfilepath);
break;
}
In the Fileoperator class I tried to make a couple methods to enable saving (from inputs from the screen to a text file) and loading (from exactly the same text file and print it out on screen). Since both of them are static methods, I can't quote them directly in my FileoperatorTest. How could I write the tests for them?
(I've already written some tests for Person.)
public class Fileoperator {
private ArrayList<Person> saveList;
private Scanner scanner;
int age;
String name;
int income;
int expenditure;
int willingnesstoInvest;
String exit;
public Fileoperator() {
saveList = new ArrayList<>();
scanner = new Scanner(System.in);
processOperations();
}
private void processOperations() {
while (true) {
Person personEntry = getPerson();
if (exit.equals("yes")) {
personEntry.updateMaster(age, name, income, expenditure, willingnesstoInvest);
personResult(personEntry);
break;
}
personEntry.updateMaster(age, name, income, expenditure, willingnesstoInvest);
personResult(personEntry);
System.out.println(personEntry.print());
}
for (Person p: saveList) {
System.out.println(p.print());
}
}
private Person getPerson() {
Person personEntry = new Person(0, "", 0, 0, 0);
System.out.println("Age: ");
age = scanner.nextInt();
scanner.nextLine();
System.out.println("Name: ");
name = scanner.nextLine();
System.out.println("Income: ");
income = scanner.nextInt();
System.out.println("Expenditure:");
expenditure = scanner.nextInt();
System.out.println("Willingness to invest: ");
willingnesstoInvest = scanner.nextInt();
scanner.nextLine();
System.out.println("done?(yes or no)");
exit = scanner.nextLine();
return personEntry;
}
private void personResult(Person p) {
saveList.add(p);
}
public static void mainhelper() {
try {
printload(load());
} catch (IOException e) {
e.printStackTrace();
}
Fileoperator fo = new Fileoperator();
try {
fo.save();
} catch (IOException e) {
e.printStackTrace();
}
}
public void save() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("output.txt"));;
PrintWriter writer = new PrintWriter("output.txt","UTF-8");
for (Person p: saveList) {
lines.add(p.getAge() + ", " + p.getName() + ", "
+ p.getIncome() + ", " + p.getExpenditure() + ", " + p.getwillingnesstoInvest());
}
for (String line : lines) {
ArrayList<String> partsOfLine = splitOnSpace(line);
System.out.println("Age: " + partsOfLine.get(0) + ", ");
System.out.println("Name: " + partsOfLine.get(1) + ", ");
System.out.println("Income " + partsOfLine.get(2) + ", ");
System.out.println("Expenditure " + partsOfLine.get(3) + ", ");
System.out.println("WillingnesstoInvest " + partsOfLine.get(4) + ", ");
writer.println(line);
}
writer.close(); //note -- if you miss this, the file will not be written at all.
}
public static ArrayList<String> splitOnSpace(String line) {
String[] splits = line.split(", ");
return new ArrayList<>(Arrays.asList(splits));
}
public static ArrayList<Person> load() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("output.txt"));
ArrayList<Person> loadList = new ArrayList();
for (String line : lines) {
if (line.equals("")) {
break;
} else {
Person fromline = fromline(line);
loadList.add(fromline);
}
}
return loadList;
}
public static void printload(ArrayList<Person> loadList) {
for (Person p: loadList) {
System.out.println(p.print());
}
}
private static Person fromline(String line) {
Person fromline = new Person(0, "", 0, 0, 0);
ArrayList<String> partsOfLine = splitOnSpace(line);
int age = Integer.parseInt(partsOfLine.get(0));
int income = Integer.parseInt(partsOfLine.get(2));
int expenditure = Integer.parseInt(partsOfLine.get(3));
int willingnesstoInvest = Integer.parseInt(partsOfLine.get(4));
fromline.updateMaster(age, partsOfLine.get(1), income, expenditure, willingnesstoInvest);
return fromline;
}
}
So my question is how can i Delete/not display the nulls,the excess not founds,and 0's when I run the program, also the last two attributes of the Student201 when 'runned', it displays in reverse order meaning the the nulls or the excess not founds or zeroes are displayed first.
also how can I add students 'predefined'
This is my preferred output or display as much as possible w/o the not found
This is not what I want, the not founds are printed first before the desired output
Main.java
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Student a1=new Student();
//a1.choosy();
Student201 a2 =new Student201();
a2.studinfo();
a2.findstud("2000000001);
}
}
Student201.java
public class Student201 {
Student [] studarray = new Student[13];
int x;
public void studinfo()
{
for (x=0;x<studarray.length;x++) {
studarray[x]= new Student();
}
Student estudyante1 = new Student();
Student estudyante2 = new Student ();
Student estudyante3 = new Student ();
Student estudyante4 = new Student ();
Student estudyante5 = new Student ();
estudyante1.getStudName("Yves Francisco");
estudyante1.getStudNum(2000000001);
estudyante1.getYrLvl(5);
estudyante1.getKors("CpE");
estudyante1.getGender("Male");
estudyante2.getStudName("Lance Eco");
estudyante2.getStudNum(2000000002);
estudyante2.getYrLvl(5);
estudyante2.getKors("CpE");
estudyante2.getGender("Male");
estudyante3.getStudName("Karlos Castillo");
estudyante3.getStudNum(2000000003);
estudyante3.getYrLvl(5);
estudyante3.getKors("CpE");
estudyante3.getGender("Male");
estudyante4.getStudName("Glenn Bordonada");
estudyante4.getStudNum(2000000004);
estudyante4.getYrLvl(4);
estudyante4.getKors("ECE");
estudyante4.getGender("Male");
estudyante5.getStudName("Tim Tolentino");
estudyante5.getStudNum(2000000005);
estudyante5.getYrLvl(4);
estudyante5.getKors("ECE");
estudyante5.getGender("Male");
studarray[0]=estudyante1;
studarray[1]=estudyante2;
studarray[2]=estudyante3;
studarray[3]=estudyante4;
studarray[4]=estudyante5;
}
public void findstud (String query) //String query for searching
{
int ercatch=0;
try{
ercatch=Integer.parseInt(query);
}
catch (NumberFormatException m)
{
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setStudName())) //query.equalsIgnorecase for case sensitive inputs
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender()+"\n");
System.out.println("\n");
}
}
for (x=0;x<studarray.length;x++)
{
if (ercatch == studarray[x].setStudNum()) //Integer.parseInt for int data types
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
else if (ercatch != studarray[x].setStudNum())
{
System.out.println("Not Found!");
}
}
for (x=0;x<studarray.length;x++)
{
if (ercatch == studarray[x].setYrLvl())
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
else if (ercatch != studarray[x].setYrLvl())
{
System.out.println("Not Found!");
}
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setKors()))
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setGender()))
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
}
}
public void addstud (String query)
{
}
}
Student.Java
public class Student {
private String StudName;
private int StudNum;
private int YrLvl;
private String Kors;
private String Gender;
//this just for naming convention for the get and set
public void getStudName (String name) {
this.StudName=name;
}
public String setStudName() {
return StudName;
}
public void getStudNum (int numero) {
this.StudNum=numero;
}
public int setStudNum() {
return StudNum;
}
public void getYrLvl (int yrlvl) {
this.YrLvl=yrlvl;
}
public int setYrLvl()
{
return YrLvl;
}
public void getKors (String korse) {
this.Kors=korse;
}
public String setKors() {
return Kors;
}
public void getGender (String sex)
{
this.Gender=sex;
}
public String setGender() {
return Gender;
}
public void choosy() {
System.out.println("Here is the list and the information of the Students \n");
}
/*public static void main(String[] args) {
// TODO Auto-generated method stub
}*/
}
First things first, you have totally mixed up getters and setters, getters should return the value without any parameter, and setters set the field to a vala ue with parameter, like this
public void setStudName (String name) {
this.StudName=name;
}
public String getStudName() {
return StudName;
}
public void setStudNum (int numero) {
this.StudNum=numero;
}
public int getStudNum() {
return StudNum;
}
Since you don't want to display the Not found result, so I remove it and this is your Student201 class.
public class Student201 {
Student[] studarray = new Student[13];
int x;
public void studinfo() {
for (x = 0; x < studarray.length; x++) {
studarray[x] = new Student();
}
Student estudyante1 = new Student();
Student estudyante2 = new Student();
Student estudyante3 = new Student();
Student estudyante4 = new Student();
Student estudyante5 = new Student();
estudyante1.setStudName("Yves Francisco");
estudyante1.setStudNum(2000000001);
estudyante1.setYrLvl(5);
estudyante1.setKors("CpE");
estudyante1.setGender("Male");
estudyante2.setStudName("Lance Eco");
estudyante2.setStudNum(2000000002);
estudyante2.setYrLvl(5);
estudyante2.setKors("CpE");
estudyante2.setGender("Male");
estudyante3.setStudName("Karlos Castillo");
estudyante3.setStudNum(2000000003);
estudyante3.setYrLvl(5);
estudyante3.setKors("CpE");
estudyante3.setGender("Male");
estudyante4.setStudName("Glenn Bordonada");
estudyante4.setStudNum(2000000004);
estudyante4.setYrLvl(4);
estudyante4.setKors("ECE");
estudyante4.setGender("Male");
estudyante5.setStudName("Tim Tolentino");
estudyante5.setStudNum(2000000005);
estudyante5.setYrLvl(4);
estudyante5.setKors("ECE");
estudyante5.setGender("Male");
studarray[0] = estudyante1;
studarray[1] = estudyante2;
studarray[2] = estudyante3;
studarray[3] = estudyante4;
studarray[4] = estudyante5;
}
public void findstud(String query) //String query for searching
{
int ercatch = 0;
try {
ercatch = Integer.parseInt(query);
} catch (NumberFormatException m) {
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getStudName())) //query.equalsIgnorecase for case sensitive inputs
{
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender() + "\n");
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (ercatch == studarray[x].getStudNum()) //Integer.parseInt for int data types
{
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (ercatch == studarray[x].getYrLvl()) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getKors())) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getGender())) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
}
public void addstud(String query) {
}
}
how can i Delete/not display the nulls,the excess not founds,and 0's
First, remove this
for (x=0;x<studarray.length;x++) {
studarray[x]= new Student();
}
Then, all the students are null except for those you defined, which you can explicitly ignore them.
for (int x = 0; x < studarray.length; x++) {
Student s = studarray[x];
if (s == null) {
continue; // here
}
// Check all your fields in a single loop
if (query.equalsIgnoreCase(s.getStudName())) {
} else if (Integer.parseInt(query) == s.getStudNum()) {
} else {
System.out.println("Student not found using query " + query);
}
}
Here is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list == null;
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args){
while(true){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
while (empList.hasItems()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
// int choose;
// do{
//
//
// System.out.println("\nGo back to main?<1=Yes/0=No>: \n");
// choose = sc.nextInt();
// }while (choose != 1);
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
Case 2 shows no error but when I run it on the IDE it shows:
Exception in thread "main" java.util.NoSuchElementException at
java.util.LinkedList.getFirst(Unknown Source) at
GenQueue.getFirst(something.java:44) at
something.main(something.java:113)
Any idea why this happen? and how to fix it? Your help will be very much appreciated, from python I just went Java today, newbie here.
NoSuchElementException is thrown by LinkedList.getFirst when the list is empty.
You should handle that particular case before calling that method, for example:
if (!empList.hasItems()) {
System.out.println("The queue is empty!");
} else {
System.out.println("First in queue: " +empList.getFirst());
... // rest of code
}