ArrayList gets overwritten everytime a new instance is created - java

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(....);

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

Sorting multiple arraylists in Java

I'm trying to figure out how to sort the arrayLists that come out of a .txt file. I want to be able to sort them alphabetically by name. Here is an example of how the txt file is listed:
Alvarez, Eliezer
74
2B
IA
22
Bowman, Matt
67
P
A
26
Each piece is on a single line by itself (except lastName, firstName being on a line together).
Is there a way to do a collections sort that will adjust the rest of the Arraylists based off the name Arraylist? Thanks.
Scanner keyboard = new Scanner(System.in);
String filename;
fileName = "cardinals.txt";
File baseball = new File(fileName);
if (!baseball.exists()) {
System.out.println("The input file was not found.");
System.exit(0);
}
ArrayList<String> name = new ArrayList<>();
ArrayList<Integer> number = new ArrayList<>();
ArrayList<String> position = new ArrayList<>();
ArrayList<String> status = new ArrayList<>();
ArrayList<Double> age = new ArrayList<>();
Scanner stats = new Scanner(baseball);
if (!stats.hasNext()) {
System.out.println("The file is empty.");
}
else {
while (stats.hasNext()) {
name.add(stats.nextLine());
number.add(stats.nextInt());
position.add(stats.next());
status.add(stats.next());
age.add(stats.nextDouble());
try {
stats.nextLine();
} catch (Exception e) {
}
}
} stats.close();
sortArrayPosition();
sortArrayPosition (ArrayList<String> name, ArrayList<Integer> number, ArrayList<String> position, ArrayList<String> status, ArrayList<Double> age) {
When organizing and managing complex data, using an object to group the data together is the best approach.
Here is an example using an object to store the information:
package example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
class StatisticsReader {
private static class PlayerStats {
String name;
Integer number;
String position;
String status;
Double age;
public PlayerStats(String name, Integer number, String position, String status, Double age) {
this.name = name;
this.number = number;
this.position = position;
this.status = status;
this.age = age;
}
#Override
public String toString() {
return "PlayerStats{" +
"name='" + name + '\'' +
", number=" + number +
", position='" + position + '\'' +
", status='" + status + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
File baseball = new File("cardinals.txt");
if (!baseball.exists()) {
System.out.println("The input file was not found.");
System.exit(0);
}
List<PlayerStats> statsList = new ArrayList<>();
try (Scanner stats = new Scanner(baseball)) {
if (!stats.hasNext()) {
System.out.println("The file is empty.");
}
else {
while (stats.hasNext()) {
String name = stats.nextLine();
Integer number = stats.nextInt();
String position = stats.next();
String status = stats.next();
Double age = stats.nextDouble();
statsList.add(new PlayerStats(name, number, position, status, age));
stats.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
statsList.sort(Comparator.comparing(o -> o.name));
statsList.forEach(System.out::println);
}
}
You can customize the toString() method to change the output if necessary.

how to fix up code with java display

import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
class Enrolment{
public static void main(String[] args)
{
System.out.println("/*-------------------------------------");
System.out.println("My name: XIANGYU QIAO");
System.out.println("My student number: 5089864");
System.out.println("My email address: xq907#uowmail.edu.au");
System.out.println("Assignment number: 2");
System.out.println("-------------------------------------*/");
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
class Student{
private static Formatter outStream;
private static Scanner inStream;
public Student() throws IOException
{
outStream = new Formatter(new File("student1.txt"));
String fullName = "David Black";
String email = "davblk#ipw.edu.au";
String course = "1853E";
sNumber = 375428;
outStream.format("%s %s %s %i", fullName, email, course, sNumber);
outStream.close();
inStream = new Scanner( new File("student1.txt"));
String Fullname = inStream.next();
String Email = inStream.next();
String Course = inStream.next();
int Studentnumber = inStream.nextInt();
inStream.close();
}
public void displayStudInfo()
{
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
}
}
class Subject{
private static Formatter outStream;
private static Scanner inStream;
public Subject() throws IOException
{
outStream = new Formatter(new File("subject1.txt"));
String sCode = "CSIT455";
String session = "Autmn";
int year = 2017;
outStream.format("%s %s %i", sCode, session, year);
outStream.close();
inStream = new Scanner( new File("subject1.txt"));
String Subjectcode = inStream.next();
String Session = inStream.next();
int Year = inStream.nextInt();
inStream.close();
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
i am trying to create a file of student information and display it but i could not find a way to do that. could anyone help me to fix the code?
i am asked to display the student information in class Enrolment(main method here)and subject information that is given in class Student and Subject.i have no idea how to link these three things though it requires to use displayStudInfo method in class Student and displaySubjectInfo in class Subject.
If I correctly understand, you cannot access properties from constructor in displayStudInfo method. So assigning those properties to class properties will resolve the issue.
class Student {
private final String fullname;
private final String email;
private final String course;
private final int studentNumber;
public Student() throws IOException {
writeStudent();
Scanner inStream = new Scanner(new File("student1.txt"));
fullname = inStream.next();
email = inStream.next();
course = inStream.next();
studentNumber = inStream.nextInt();
inStream.close();
}
private void writeStudent() throws FileNotFoundException {
Formatter outStream = new Formatter(new File("student1.txt"));
outStream.format("%s %s %s %i", "David Black", "davblk#ipw.edu.au", "1853E", 375428);
outStream.close();
}
public void displayStudInfo() {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}
}
If you do not want to add any more class prop, you will need to ad arguments to your method:
public void displayStudInfo( String fullname,String email,String course, int studentNumber) {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}

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