How to write tests for my static methods? - java

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;
}
}

Related

Expression expected in switch case method call

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;
}

How can I delete/not display the nulls?

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);
}
}

Printing textdata from toString - Java

I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?
This is how my toString looks like:
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
Full code:
import java.util.*;
import java.io.*;
public class Codes {
public static void main(String[] args) {
List<Codes2> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] personData = fileRead.split(":");
String personName = personData[0];
String userNameGenerator = personData[1];
Codes2 personObj = new Codes2(personName, userNameGenerator);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++){
String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
for(int j = 0; j < regionSplit.length; j++){
newStrSet.add(regionSplit[j]);
}
}
for (String p: newStrSet) {
System.out.printf("%s -> ", p);
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.getPersonName());
}
}
System.out.println();
}
}
}
Java Class:
public class Codes2 implements Comparable<Codes2> {
private String personName;
private String userNameGenerator;
public Codes2(String personName, String userNameGenerator) {
this.personName = personName;
this.userNameGenerator = userNameGenerator;
}
public String getPersonName() {
return personName;
}
public String getUserNameGenerator() {
return userNameGenerator;
}
#Override
public int compareTo(Codes2 o) {
return getUserNameGenerator().compareTo(o.getUserNameGenerator());
}
public int compare(Object lOCR1, Object lOCR2) {
return ((Codes2)lOCR1).userNameGenerator
.compareTo(((Codes2)lOCR2).userNameGenerator);
}
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
}
Everything looks right in your code.
I think you should just call the method when you are trying to print it out:
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.toString());
}
}
This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.
Try:
#Override
public String toString() {
return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}

Queues and Stacks Hiring and Firing

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.");
}
}

fill arrayList with dat file

Here's the code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib
{
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib()
{
loadNouns();
loadVerbs();
loadAdjectives();
out.println(nouns);
}
public MadLib(String fileName)
{
//load stuff
loadNouns();
loadVerbs();
loadAdjectives();
try{
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e)
{
out.println("Houston we have a problem!");
}
}
public void loadNouns()
{
nouns = new ArrayList<String>();
try{
//nouns = new ArrayList<String>();
String nou = "";
Scanner chopper = new Scanner(new File ("nouns.dat"));
//chopper.nextLine();
while(chopper.hasNext()){
nou = chopper.next();
out.println(nou);
nouns.add(nou);
//chopper.nextLine();
}
//chopper.close();
out.println(nouns.size());
}
catch(Exception e)
{
out.println("Will");
}
}
public void loadVerbs()
{
verbs = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("verbs.dat"));
while(chopper.hasNext()){
verbs.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
out.println("run");
}
}
public void loadAdjectives()
{
adjectives = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("adjectives.dat"));
while(chopper.hasNext()){
adjectives.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
}
}
public String getRandomVerb()
{
String verb = "";
int num = 0;
num = (int)(Math.random()*(verbs.size()-1));
verb = verbs.get(num);
return verb;
}
public String getRandomNoun()
{
String noun = "";
int num = 0;
if(nouns == null){
loadNouns();
}
double rand = (Math.random());
num = (int)(rand * (nouns.size()-1));
out.println(num);
noun = nouns.get((int) num);
out.print(noun);
return noun;
}
public String getRandomAdjective()
{
String adj = "";
int num = 0;
num = (int)(Math.random()*(adjectives.size()-1));
adj = adjectives.get(num);
return adj;
}
public String toString()
{
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
and here's one of the .dat files (the other 2 are the exact same aside from the specific words they contain):
dog
pig
chicken
building
car
person
place
thing
truck
city
state
school
student
bird
turkey
lion
tiger
alligator
elephant
My issue is that I can't get any of my arrayLists to read in their appropriate .dat files and from my POV, my code seems like it should do that
UPDATE
current output aside from the absence of "Will" (I removed that line):
run
[ ]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MadLib.getRandomNoun(MadLib.java:130)
at MadLib.toString(MadLib.java:147)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at Lab16d.main(Lab16d.java:18)
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public static void main(String args[]) {
MadLib a = new MadLib();
System.out.println(a.toString());
}
public MadLib() {
loadAllWords();
System.out.println(nouns);
}
public MadLib(String fileName) {
loadAllWords();
try {
Scanner file = new Scanner(new File(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadAllWords() {
loadNouns();
loadVerbs();
loadAdjectives();
}
public void loadNouns() {
nouns = loadFile("nouns.dat");
}
public void loadVerbs() {
verbs = loadFile("verbs.dat");
}
public void loadAdjectives() {
adjectives = loadFile("adjectives.dat");
}
public ArrayList<String> loadFile(String filename) {
ArrayList<String> words = new ArrayList<String>();
try {
Scanner chopper = new Scanner(new File(filename));
while (chopper.hasNext()) {
words.add(chopper.next());
// just calling nextLine will cause an exception at the end of the file unless you have an blank line there on purpose, so this makes sure it does
if (chopper.hasNext()) {
chopper.nextLine();
}
}
chopper.close();
} catch (Exception e) {
e.printStackTrace();
}
return words;
}
public String getRandomWord(ArrayList<String> words) {
Random rand = new Random();
int num = rand.nextInt(words.size());
String word = nouns.get(num);
System.out.println(word);
return word;
}
public String getRandomVerb() {
if (verbs == null) {
loadNouns();
}
return getRandomWord(verbs);
}
public String getRandomNoun() {
if (nouns == null) {
loadNouns();
}
return getRandomWord(nouns);
}
public String getRandomAdjective() {
if (adjectives == null) {
loadNouns();
}
return getRandomWord(adjectives);
}
public String toString() {
return "The " + getRandomNoun() + " " + getRandomVerb() + " after the " + getRandomAdjective() + " " + getRandomAdjective() + " " + getRandomNoun() + " while the " + getRandomNoun() + " " + getRandomVerb() + " the " + getRandomNoun();
}
}

Categories

Resources