Expression expected in switch case method call - java

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

Related

Actual and formal argument lists differ in length error in main

Im working on a project where I have 3 text files with data of doctors, patients and home visits. When Im trying to upload the doctors file, upload all the data to a new object I get an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Id_pacjenta Nazwisko Imie PESEL Data_urodzenia"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at com.company.Main.main(Main.java:40)
Below I'll paste my main as well as the classes & a snapshot of the text file used for imports:
Could anyone advise how to avoid this issue? Thanks!
public class Main {
public static void main(String[] args) {
List<Lekarz> lekarz = new ArrayList<>();
try{
File fileLekarze = new File("src/com/company/lekarze.txt");
Scanner readerLekarze = new Scanner(fileLekarze);
while(readerLekarze.hasNextLine()){
String[] data =readerLekarze.nextLine().split(" ");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
readerLekarze.close();
} catch (FileNotFoundException e) {
System.out.println("Error File Lekarze");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
List<Pacjenci> pacjent = new ArrayList<>();
try{
File pacjenciFile = new File("src/com/company/pacjenci.txt");
Scanner readerPacjenci = new Scanner(pacjenciFile);
while(readerPacjenci.hasNextLine()){
String[] data = readerPacjenci.nextLine().split(" ");
pacjent.add(new Pacjenci(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}
readerPacjenci.close();
}catch (FileNotFoundException e) {
System.out.println("Error File Pacjenci");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
}
}
public class Pacjenci {
private int idPacjenta;
private String nazwisko;
private String imie;
private String pesel;
private Date dataUrodzenia;
public Pacjenci(int idPacjenta, String nazwisko, String imie, String pesel, Date dataUrodzenia) {
this.idPacjenta = idPacjenta;
this.nazwisko = nazwisko;
this.imie = imie;
this.pesel = pesel;
this.dataUrodzenia = dataUrodzenia;
}
public int getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(int idPacjenta) {
this.idPacjenta = idPacjenta;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public Date getDataUrodzenia() {
return dataUrodzenia;
}
public void setDataUrodzenia(Date dataUrodzenia) {
this.dataUrodzenia = dataUrodzenia;
}
#Override
public String toString() {
return "Pacjenci{" +
"idPacjenta=" + idPacjenta +
", nazwisko='" + nazwisko + '\'' +
", imie='" + imie + '\'' +
", pesel='" + pesel + '\'' +
", dataUrodzenia=" + dataUrodzenia +
", wizyty=" +
", lekarze=" +
'}';
}
}
public class Wizyty {
private Lekarz idLekarza;
private Pacjenci idPacjenta;
private Date dataWizyty;
public Wizyty(Lekarz idLekarza, Pacjenci idPacjenta, Date dataWizyty) {
this.idLekarza = idLekarza;
this.idPacjenta = idPacjenta;
this.dataWizyty = dataWizyty;
}
public Lekarz getIdLekarza() {
return idLekarza;
}
public void setIdLekarza(Lekarz idLekarza) {
this.idLekarza = idLekarza;
}
public Pacjenci getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(Pacjenci idPacjenta) {
this.idPacjenta = idPacjenta;
}
public Date getDataWizyty() {
return dataWizyty;
}
public void setDataWizyty(Date dataWizyty) {
this.dataWizyty = dataWizyty;
}
#Override
public String toString() {
return "Wizyty{" +
"idLekarza=" + idLekarza +
", idPacjenta=" + idPacjenta +
", dataWizyty=" + dataWizyty +
'}';
}
}
Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
100 Kowal Waldemar 01211309876 2001-1-13
Because of the data spacing in the file, try this:
while(readerLekarze.hasNextLine()){
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim()
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
You could also just do:
String[] data = readerLekarze.nextLine().trim().split("\\s+");
As a complement to the #DevilsHnd, you only need to add a code to avoid the first line, because the first line is the "header information" of your file.
boolean headerRead = false;
while(readerLekarze.hasNextLine()) {
if (!headerRead) {
// extract the first line -> Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
readerLekarze.nextLine();
headerRead = true;
continue;
}
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim();
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(
Integer.parseInt(data[0]),
data[1],
data[2],
data[3],
new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}

ArrayList gets overwritten everytime a new instance is created

I'm a new programmer,
I'm terribly sorry for the walls of code, but I simply can't find the error.
I am tring to create an arrayList that stores input values, but everytime I create the 2nd instance, the first instance gets overwritten. It does print two instances, but both instances have the same value.
Main block:
The problem area is at the bottom of this code, "switch sc1" and "switch s2, case 2"
package com.company;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
User user = new User(null, null, null, null, null);
Login login = new Login(null, null, null, null, null);
Stream stream = new Stream(null, null, null, null, 0, null, null);
List list = new List(null, null, null, null, 0, null, null);
ArrayList<Stream> joinableList = new ArrayList<Stream>();
ArrayList<Stream> completedList = new ArrayList<Stream>();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM-yyyy HH:mm");
boolean showRoom = false;
while (showRoom == false) {
System.out.println("\nWelcome to ShowRoom\n\nPress 1 to login\nPress 2 to create a user\n");
Scanner choice1 = new Scanner(System.in);
System.out.print("Input: ");
int s1 = choice1.nextInt();
switch (s1) {
case 1:
System.out.print("\nEnter Username: ");
Scanner scanUsername = new Scanner(System.in);
String username = scanUsername.nextLine();
user.setUsername(username);
System.out.print("\nEnter Password: ");
Scanner scanPassword = new Scanner(System.in);
String password = scanPassword.nextLine();
user.setPassword(password);
login.verifyLogin(username, password);
break;
case 2:
System.out.print("\nChoose Username: ");
Scanner scanChooseUsername = new Scanner(System.in);
username = scanChooseUsername.nextLine();
user.setUsername(username);
user.saveUsername();
System.out.print("\nChoose Password: ");
Scanner scanChoosePassword = new Scanner(System.in);
password = scanChoosePassword.nextLine();
user.setPassword(password);
user.savePassword();
break;
}
boolean loggedIn = false;
while (loggedIn == false) {
System.out.println("\nWelcome to your dashboard " + user.username + "\n\nPress 1 to create a stream\nPress 2 to view joinable streams\nPress 3 to view completed streams");
Scanner choice2 = new Scanner(System.in);
System.out.print("\nInput: ");
int s2 = choice2.nextInt();
switch (s2) {
case 1:
String listUsername = user.username;
stream.setListUsername(user.username);
Scanner chooseTitle = new Scanner(System.in);
System.out.print("\nChoose title: ");
String title = chooseTitle.nextLine();
stream.setTitle(title);
System.out.println("\nYou have chosen: " + stream.title);
Scanner chooseGenre = new Scanner(System.in);
System.out.print("\nChoose genre:\n\nPress 0 for " + stream.genreArray[0] + "\nPress 1 for " + stream.genreArray[1] + "\nPress 2 for " + stream.genreArray[2] + "\n\nInput: ");
int chosenGenre = chooseGenre.nextInt();
String genre = stream.genreArray[chosenGenre];
stream.setGenre(genre);
System.out.println("\nYou have chosen: " + stream.genre);
Scanner chooseType = new Scanner(System.in);
System.out.print("\nChoose type:\n\nPress 0 for " + stream.typeArray[0] + "\nPress 1 for " + stream.typeArray[1] + "\nPress 2 for " + stream.typeArray[2] + "\n\nInput: ");
int chosenType = chooseType.nextInt();
String type = stream.typeArray[chosenType];
stream.setType(type);
System.out.println("\nYou have chosen: " + stream.type);
Scanner choosePrice = new Scanner(System.in);
System.out.print("\nChoose price: ");
double price = choosePrice.nextDouble();
stream.setPrice(price);
System.out.println("\nYou have chosen: " + stream.price);
Scanner chooseStartTimeDate = new Scanner(System.in);
System.out.print("\nChoose start time and date: \n\nInsert time and date in this format: dd/mm-yyyy hh:mm\n\nInput: ");
String startTimeDate = chooseStartTimeDate.nextLine();
stream.setStartTimeDate(startTimeDate);
System.out.println("\nYou have chosen " + stream.startTimeDate);
Scanner chooseEndTimeDate = new Scanner(System.in);
System.out.print("\nChoose end time and date: \n\nInsert time and date in this format: dd/mm-yyyy hh:mm\n\nInput: ");
String endTimeDate = chooseEndTimeDate.nextLine();
stream.setEndTimeDate(endTimeDate);
System.out.println("\nYou have chosen " + stream.endTimeDate);
Scanner confirmStream = new Scanner(System.in);
System.out.print("\nDo you want to create a stream, with the following details?\n\nTitle: " + title + "\nGenre: " + genre + "\nType: " + type + "\nPrice: " + price + "\nStart date and time: " + startTimeDate + "\nEnd date and time: " + endTimeDate + "\n\nPress 1 to confirm\nPress 2 to go back\n\nInput: ");
int sc1 = confirmStream.nextInt();
switch (sc1) {
case 1:
list.addJoinableList(stream);
System.out.println("\nStream has been created and added to list");
loggedIn = false;
break;
case 2:
loggedIn = false;
break;
}
case 2:
list.printJoinableList();
break;
case 3:
System.out.println("\nCompleted stream list");
break;
}
}
}
}
}
Stream block:
This block is used to inherit the properties for use in the class "List"
package com.company;
import java.time.LocalDateTime;
public class Stream {
protected String listUsername;
protected String title;
protected String genre;
protected String type;
protected double price;
protected String startTimeDate;
protected String endTimeDate;
public Stream (String listUsername, String title, String genre, String type, double price, String startTimeDate, String endTimeDate) {
this.listUsername = listUsername;
this.title = title;
this.genre = genre;
this.type = type;
this.price = price;
this.startTimeDate = startTimeDate;
this.endTimeDate = endTimeDate;
}
String genreArray[] = {"Comedy", "Lifestyle", "Music"};
String typeArray[] = {"Entertainment", "Familiy", "Work"};
public String getListUsername() { return listUsername; }
public void setListUsername(String listUsername) { this.listUsername = listUsername; }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStartTimeDate() {
return startTimeDate;
}
public void setStartTimeDate(String startTimeDate) {
this.startTimeDate = startTimeDate;
}
public String getEndTimeDate() { return endTimeDate; }
public void setEndTimeDate(String endTimeDate) { this.endTimeDate = endTimeDate;}
}
List block:
I think that the main issues are here, but I just can't figure out what is wrong.
package com.company;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class List extends Stream {
public List(String listUsername, String title, String genre, String type, double price, String startTimeDate, String endTimeDate) {
super(listUsername, title, genre, type, price, startTimeDate, endTimeDate);
}
ArrayList<Stream> joinableList = new ArrayList<Stream>();
ArrayList<Stream> completedList = new ArrayList<Stream>();
public void addJoinableList(Stream stream) {
joinableList.add(stream);
}
public void printJoinableList() {
for (Stream s : joinableList) {
System.out.print("\nUsername: " + s.getListUsername());
System.out.print("\nTitle: " + s.getTitle());
System.out.print("\nGenre: " + s.getGenre());
System.out.print("\nType: " + s.getType());
System.out.print("\nPrice: " + s.getPrice());
System.out.print("\nStart time and date: " + s.getStartTimeDate());
System.out.print("\nEnd time and date: " + s.getEndTimeDate() + "\n");
}
}
}
All help is appreciated, thank you.
When I see object created once like this:
User user = new User(null, null, null, null, null);
And then, no new User, I understand that you never create new instance of your object.
The rest of the code is in the same vein: you are (almost) creating only one instance of an object, rather than a new instance.
Therefore, when you change a property of said instance, it affect all objects.
You need to add somewhere in your code, when you feel that with the data entered by the user (and read by the Scanner), you may create a new User, Stream, ...
For example, after this:
list.addJoinableList(stream);
Do:
stream = new Stream(....);

How to write tests for my static methods?

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

Java Obtaining the First Element and Then Removing that First Element Printing the Rest of the Elements

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
}

Element update for Java Util List [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an ArrayList for Patients in little hospital system and need to write a method to update the patient information. This method should take an integer called "id", match this id with all id's in Patient ArrayList and change some information in that object. How can I iterate this list? Thanks.
This is my Patient Class
import java.util.ArrayList;
import java.util.List;
public class Patient {
String strName,strSurname,strAddress,strDepartment,strGender;
int iId,iClass,iDob;
List<Entry> entries = new ArrayList<Entry>();
long longTel;
boolean boolAllergy,boolChronicDisease,boolRegularMedicine;
public boolean isBoolAllergy() {
return boolAllergy;
}
public void setBoolAllergy(boolean boolAllergy) {
this.boolAllergy = boolAllergy;
}
public boolean isBoolChronicDisease() {
return boolChronicDisease;
}
public void setBoolChronicDisease(boolean boolChronicDisease) {
this.boolChronicDisease = boolChronicDisease;
}
public boolean isBoolRegularMedicine() {
return boolRegularMedicine;
}
public void setBoolRegularMedicine(boolean boolRegularMedicine) {
this.boolRegularMedicine = boolRegularMedicine;
}
public String getStrName() {
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
}
public String getStrSurname() {
return strSurname;
}
public void setStrSurname(String strSurname) {
this.strSurname = strSurname;
}
public String getStrAddress() {
return strAddress;
}
public void setStrAddress(String strAddress) {
this.strAddress = strAddress;
}
public String getStrDepartment() {
return strDepartment;
}
public void setStrDepartment(String strDepartment) {
this.strDepartment = strDepartment;
}
public int getiId() {
return iId;
}
public void setiId(int iId) {
this.iId = iId;
}
public long getlongTel() {
return longTel;
}
public void setiTel(long iTel) {
this.longTel = iTel;
}
public int getiClass() {
return iClass;
}
public void setiClass(int iClass) {
this.iClass = iClass;
}
public int getiDob() {
return iDob;
}
public void setiDob(int iDob) {
this.iDob = iDob;
}
public String getStrGender() {
return strGender;
}
public void setStrGender(String strGender) {
this.strGender = strGender;
}
public void Details() {
System.out.println("*********************************");
System.out.println("Patient Id: " + getiId());
System.out.println("Name: " + getStrName() + " Surname: " + getStrSurname());
System.out.println("Address: " + getStrAddress() + " Department: " + getStrDepartment() + " Gender: " + getStrGender());
System.out.println("Class: " + getiClass() + " Date of birth: " + getiDob() + " Tel: " + getlongTel());
System.out.println("Chronical Disease? " + isBoolChronicDisease());
System.out.println("Any Allergy? " + isBoolAllergy());
System.out.println("Using regular drugs?" + isBoolRegularMedicine());
System.out.println("*********************************");
}
}
And this is the main class that uses Patient class
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Main {
static List<Doctor> listDoctors = new ArrayList<Doctor>();
static List<Nurse> listNurses = new ArrayList<Nurse>();
static List<Patient> listPatients = new ArrayList<Patient>();
static String strUserName = "admin";
static String strPass = "password";
public static void main(String[] args) {
#SuppressWarnings("unused")
int iChoice;
boolean exit = false;
boolean boolAccess = Login();
if (boolAccess) {
while(!exit) {
iChoice = Menu();
switch(iChoice) {
case 1:
AddDoctor();
break;
case 2:
AddNurse();
break;
case 3:
AddPatient();
break;
case 4:
ListDoctors();
break;
case 5:
ListNurses();
break;
case 6:
ListPatients();
break;
case 8:
ChangeUserName();
break;
case 9:
ChangePass();
break;
//Hastalığa göre hastalar listelenecek
//Kronik hastlalıkları olan hastalar listelenecek
//Sigortasını yatırmayan hastalar listelenecek
//delete ve update olayları
//Hastaneye sevkedilen hastalar listelenecek
//Yatılı kalan hastalar listelensin
//Raporlu olan entryler listelenecek
//Kayıt girilirken eğer hasta ismi ilk defa giriliyorsa önce hasta kaydı yapın diye uyarı cıkacak
case 15:
exit = true;
break;
}
}
}
}
private static void ChangeUserName() {
Scanner scan = new Scanner(System.in);
if(Login()) {
System.out.println("Enter new User Name:");
strUserName = scan.next();
System.out.println("Saved..");
}
}
private static void ChangePass() {
Scanner scan = new Scanner(System.in);
if(Login()) {
System.out.println("Enter new Password:");
strPass = scan.next();
System.out.println("Saved..");
}
}
private static void ListNurses() {
Iterator<Nurse> it = listNurses.iterator();
while(it.hasNext()) {
Nurse nur = (Nurse) it.next();
nur.Details();
}
}
private static void ListPatients() {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
patient.Details();
}
}
public static boolean Login() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Username: ");
if(strUserName.contentEquals(scan.next())) {
System.out.println("Enter Password:");
if(strPass.contentEquals(scan.next())) {
return true;
}
else
System.out.println("Wrong password");
return Login();
}
System.out.println("Wrong user name");
return Login();
}
public static int Menu() {
Scanner scan = new Scanner(System.in);
System.out.println("Choose one of the following order:");
System.out.println("1.Enter new Doctor");
System.out.println("2.Enter new Nurse");
System.out.println("3.Enter new Patient");
System.out.println("4.List all doctors");
System.out.println("5.List all nurses");
System.out.println("6.List all patients");
System.out.println("8.Change user name");
System.out.println("9.Change password");
System.out.println("15.Exit");
return scan.nextInt();
}
private static void ListDoctors() {
Iterator<Doctor> it = listDoctors.iterator();
while(it.hasNext()) {
Doctor doc = (Doctor) it.next();
doc.Details();
}
}
private static void AddDoctor() {
Doctor doctor;
String strName,strSurname,strSpeciality;
int iSSN;
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
strName=scan.next();
System.out.println("Enter surname:");
strSurname = scan.next();
System.out.println("Enter speciality");
strSpeciality = scan.next();
System.out.println("Enter SSN");
iSSN = scan.nextInt();
doctor = new Doctor(strName,strSurname,strSpeciality,iSSN);
listDoctors.add(doctor);
System.out.println("Saved..");
}
private static void AddNurse() {
Nurse nurse;
String strName,strSurname;
int iSSN;
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
strName=scan.next();
System.out.println("Enter surname:");
strSurname = scan.next();
System.out.println("Enter SSN");
iSSN = scan.nextInt();
nurse = new Nurse(strName,strSurname,iSSN);
listNurses.add(nurse);
System.out.println("Saved..");
}
private static void AddPatient() {
Patient patient = new Patient();
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
patient.setStrName(scan.next());
System.out.println("Enter surname:");
patient.setStrSurname(scan.next());
System.out.println("Enter date of birth(DDMMYYYY)");
patient.setiDob(scan.nextInt());
System.out.println("Enter address:");
patient.setStrAddress(scan.next());
System.out.println("Enter department:");
patient.setStrDepartment(scan.next());
System.out.println("Enter gender:");
patient.setStrGender(scan.next());
System.out.println("Enter Telephone number:");
patient.setiTel(scan.nextLong());
System.out.println("Enter id:");
patient.setiId(scan.nextInt());
System.out.println("Enter class:");
patient.setiClass(scan.nextInt());
System.out.println("Does patient have any chronical disease? (Y/N)");
if(scan.next().contentEquals("Y"))
patient.setBoolChronicDisease(true);
else
patient.setBoolChronicDisease(false);
System.out.println("Does patient use any regular drugs? (Y/N)");
if(scan.next().contentEquals("Y"))
patient.setBoolRegularMedicine(true);
else
patient.setBoolRegularMedicine(false);
System.out.println("Does patient have any allergies?");
if(scan.next().contentEquals("Y"))
patient.setBoolAllergy(true);
else
patient.setBoolAllergy(false);
listPatients.add(patient);
}
private static void SearchPatientById(int id) {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
if(it.next().getiId() == id)
patient.Details();
}
}
}
With a slight modification your searchPatientById can return the found patient object:
private static Patient searchPatientById(int id) {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
if(patient.getiId() == id)
return patient;
}
// if not found return null
return null;
}
Note that I remove your double call to next()
That way, you can do something like
Patient foundPatient = searchPatientById(idToFind);
if (foundPatient != null) {
foundPatient.setBoolAllergy(patientsAllergyState);
} else {
// whatever you need to do if the patient cannot be found
}
Also note that in Java it's not common to encode the variable type into the variable names, but there's a universally followed naming convention

Categories

Resources