extracting combined string from arraylist - java

I am scanning three different inputs and converting them into a single string using toString. Then I want to edit the individual inputs.
For example:
name phoneNumber address
sarmad 12345 myhouse
How can I edit 'myhouse'?
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> arraylist = new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();
int choice;
String phoneNumber;
String name,address;
String format = "Empty";
int x = 1;
int flag = 0;
do{
try{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice = Integer.parseInt(input.next());
switch (choice){
case 1:{
System.out.println("Enter name ");
name = input.next();
System.out.println("Enter phone number");
phoneNumber = input.next();
System.out.println("Enter address");
address = input.next();
format = FormatObject.toString(phoneNumber, name, address);
arraylist.add(format);
flag++;
}
break;
case 2:{
System.out.println("Name Phone number Address");
System.out.println();
for(int i = 0; i < flag; i++){
System.out.println(arraylist.get(i));
}
}
break;
default:{
System.out.println("Enter right choice");
}
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice");
}
} while(x == 1);
}
}
my toString method:
public class CreateFormat {
String phoneNumber;
String nameUser;
String addressUser;
public String toString(){
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
public String toString (String phone,String name,String address){
phoneNumber = phone;
nameUser = name;
addressUser = address;
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
}

What you need here is to implement setters/getters for your properties.
public class CreateFormat {
private String phoneNumber;
private String nameUser;
private String addressUser;
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
// Similar set & get methods for other properties too.
}

i allowed myself to make some changes to your code, because my understanding is, that it would be easier and smother to give up String and use the Object itself instead.
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
ArrayList<CreateFormat> arrayList = new ArrayList<CreateFormat>();
int choice;
String phoneNumber;
String name; //sepperated for readability
String address;
//String format="Empty"; not used anymore
int x = 1;
//int flag = 0; is not necessary
do{
try{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice = input.nextInt();//Integer.parseInt(input.next());
switch (choice){
case 1:{
System.out.println("Enter name ");
name = input.next();
System.out.println("Enter phone number");
phoneNumber = input.next();
System.out.println("Enter address");
address = input.next();
arraylist.add(new CreateFormat(name, phoneNumber, address)); //changed to an object of type CreateFormat instead of String
//flag++; not necessary
}
break;
case 2:{
//System.out.println("Name Phone number Address");
//System.out.println();
for(int i=0;i<arrayList.size();i++){// size = method from the ArrayList library
System.out.println("Name:" + arrayList.get(i).getNameUser());
System.out.println("Phone Number:" + arrayList.get(i).getPhoneNumber());
System.out.println("Address:" + arrayList.get(i).getAddressUser());
//System.out.println(arraylist.get(i));
}
}
break;
default:{
System.out.println("Enter right choice");
}
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice");
}
}while(x==1);
}
}
Create Format:
public class CreateFormat {
String phoneNumber;
String nameUser;
String addressUser;
public CreateFormat(String phoneNumber, String nameUser, String addressUser){
this.phoneNumber = phoneNumber;
this.nameUser = nameUser;
this.addressUser = addressUser;
}
public String getPhoneNumber(){
return this.phoneNumber;
}
public String getNameUser(){
return this.nameUser;
}
public String getAddressUser(){
return this.addressUser;
}
}
I couldn't test it yet, so feel free to ask if there are some issues.

Related

Not able to execute Login method. Feel something is wrong with the object creation for populating the array: Any help is very much appreciated [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
Trying to create a bank management app. Not able to execute Login method after creating a new user. Feel something is wrong with the object creation for populating the Perons and Account arrays. Please help.
/Account class to hold account details/
public class Account extends Persons {
int accountNum;
int pin;
float checkingBal;
float savingBal;
float withDrawAmount;
float depositAmmount;
float transferAmount;
public Account(){ }
public Account(int accountNum, float checkingBal, float savingBal, int pin ){
this.accountNum = accountNum;
this.checkingBal = checkingBal;
this.savingBal = savingBal;
this.pin = pin;
}
public void setAccountNum(int accountNum){
this.accountNum = accountNum;
}
public void setPin(int pin){
this.pin = pin;
}
public int getAccountNum(){
return accountNum;
}
public int getPin(){
return pin;
}
public void withDraw(float withDrawAmount){
this.savingBal = this.savingBal - withDrawAmount;
}
public void deposit(float depositAmmount){
this.checkingBal = this.checkingBal + depositAmmount;
}
public void transfer(float transferAmount, String fromAccount, String toAccount){
if(fromAccount == "Checking" && toAccount == "Savings"){
this.checkingBal = this.checkingBal - transferAmount;
this.savingBal = this.savingBal + transferAmount;
}else if(fromAccount == "Savings" && toAccount == "Checking"){
this.savingBal = this.savingBal - transferAmount;
this.checkingBal = this.checkingBal + transferAmount;
}
System.out.print("Your New Checking Balance Is: "+this.checkingBal);
System.out.print("Your New Savings Balance Is: "+this.savingBal);
}
public float checkBalance(int accountNum){
float totalBalance = 0;
if(this.accountNum == accountNum){
totalBalance = this.checkingBal + this.savingBal;
}
return totalBalance;
}
}
/*******************************************************************************************************/
/Persons class to hold all the people having account./
import java.util.Date;
public class Persons {
String fname;
String lname;
int age;
String dob;
String address;
float yearlyIncome;
int accountNum;
public Persons(){}
public Persons(String fname, String lname, int age, String dob, String address, float yearlyIncome, int accountNum){
this.fname = fname;
this.lname = lname;
this.age = age;
this.dob = dob;
this.address = address;
this.yearlyIncome = yearlyIncome;
this.accountNum = accountNum;
}
public void setFname(String fname) {
this.fname = fname;
}
public void setLname(String lname) {
this.lname = lname;
}
public void setAge(int age) {
this.age = age;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(String address) {
this.address = address;
}
public void setYearlyIncome(float yearlyIncome) {
this.yearlyIncome = yearlyIncome;
}
public void setAccountNum(int accountNum){
this.accountNum = accountNum;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
public int getAge() {
return age;
}
public String getDob() {
return dob;
}
public String getAddress() {
return address;
}
public float getYearlyIncome() {
return yearlyIncome;
}
public int getAccountNum(){
return accountNum;
}
}
/*****************************************************************************************************/
/Java Main Class/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.Scanner;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Scanner scanf = new Scanner(System.in);
Persons people[] = new Persons[3];
Account personAccount[] = new Account[3];
float withdrawAmount;
float depositAmount;
float transferAmount;
int mainChoice;
int choice;
int counter = 0;
int userId = 0;
int loopBreak = 0;
int loginSuccess = -1;
while(loopBreak != -1){
System.out.println("================================================================================================");
System.out.println("Welcome To The California Bank :)");
System.out.println("1. Login..");
System.out.println("2. Create A New Customer.");
System.out.println("3. Done With Transactions.");
mainChoice = scanf.nextInt();
switch (mainChoice) {
case 1:
System.out.println("Please Enter Your Account Number:");
int accountNum = scanf.nextInt();
System.out.println("Please Enter Your Pin:");
int pin = scanf.nextInt();
for (int i = 0; i <= counter; i++) {
if (personAccount[i].getAccountNum() == accountNum && personAccount[i].getPin() == pin) {
System.out.println(personAccount[i].getAccountNum());
System.out.println(personAccount[i].getPin());
System.out.println("Customer Logged In and Validated.");
userId = i;
loginSuccess = 0;
} else {
System.out.println("Sorry You Are Not A Current Customer!");
loginSuccess = -1;
}
}
if(loginSuccess == 0){
System.out.println("======================================================================================");
System.out.println("What Else Would You Like To Do Today?");
System.out.println("1. Deposit.");
System.out.println("2. Withdraw.");
System.out.println("3. Transfer Money.");
System.out.println("4. Check Balance.");
choice = scanf.nextInt();
switch (choice) {
case 1:
System.out.println("How Much Money Would You Like To Deposit?");
depositAmount = scanf.nextFloat();
personAccount[userId].deposit(depositAmount);
break;
case 2:
System.out.println("How Much Money Would You Like To Withdraw Today?");
withdrawAmount = scanf.nextFloat();
personAccount[userId].withDraw(withdrawAmount);
break;
case 3:
System.out.println("How Much Money Would You Like To Withdraw Today?");
transferAmount = scanf.nextFloat();
System.out.println("1. Press 1 To Transfer From Checking to Savings.");
System.out.println("2. Press 2 To Transfer From Savings To Checking.");
int transferChoice;
transferChoice = scanf.nextInt();
if (transferChoice == 1) {
personAccount[userId].transfer(transferAmount, "Checking", "Savings");
} else {
personAccount[userId].transfer(transferAmount, "Savings", "Checking");
}
case 4:
System.out.println("Here Is Your Total Account Balance");
personAccount[userId].checkBalance(people[counter].accountNum);
break;
}
}
break;
case 2:
people[counter] = new Persons();
personAccount[counter] = new Account();
System.out.println("Please Enter Your First Name For The Account Creation:");
scanf.next();
String fName = scanf.nextLine();
System.out.println("Please Enter Your Last Name For The Account Creation:");
scanf.next();
String lName = scanf.nextLine();
people[counter].setFname(fName);
people[counter].setLname(lName);
System.out.println("Please Enter Your Age:");
int age = scanf.nextInt();
people[counter].setAge(age);
System.out.println("Please Enter Your Date Of Birth:");
String dob = scanf.next();
people[counter].setDob(dob);
System.out.println("Please Enter Your Address:");
scanf.next();
String address = scanf.nextLine();
people[counter].setAddress(address);
System.out.println("Please Enter Your Yearly Income:");
float annualIncome = scanf.nextFloat();
people[counter].setYearlyIncome(annualIncome);
System.out.println("Generating Your Account Number.....");
Random rand = new Random();
accountNum = rand.nextInt(100000);
people[counter].setAccountNum(accountNum);
personAccount[counter].setAccountNum(accountNum);
System.out.println("Your New Account Number Is: "+accountNum);
System.out.println("Please Enter A 4 Digit Pin");
pin = scanf.nextInt();
personAccount[counter].setPin(pin);
System.out.println("New Customer Created:");
counter++;
break;
case 3:
System.out.println("Thanks For Using The California Banking System. Goodbye!");
loopBreak = -1;
break;
}
}
}
}
Below is the error I am Getting after creating a user:
Login..
Create A New Customer.
Done With Transactions.
1
Please Enter Your Account Number:
90806
Please Enter Your Pin:
3333
90806
3333
Customer Logged In and Validated.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Account.getAccountNum()" because "personAccount[i]" is null
at Main.main(Main.java:48)
There are so many things about your code, but first its explanation about your bug which is NullPointerException.
This exception is thrown when you for example try to call some methods on null elements. In your case you declared array as 3 elements and add only one Account (newly created). Then you iterate on array which have null elements (2nd and 3rd are null). You should get rid of this for loop or initialize array as 1 element sized = new Account[1] and then each time copy your new accounts to new array with bigger size. But it would be terrible solution. Another way (much better
Arrays are not size dynamic so you should use one of Collections https://www.javatpoint.com/collections-in-java for example List (ArrayList would be enough). I will show you how to improve your code, hope you will learn something from it.
Ok so here is the code:
Person (not persons, shouldn't be), don't use float for money, use BigDecimal, mark your fields as private or protected (read about encapsulation), descript your fields better, not like dob - write dateOfBirth, I use LocalDate here, dont use old Time api, better look at new Java Time Api, also you can count age of user by: currentDate - dateOfBirth
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Person {
private String firstName;
private String lastName;
private int age;
private LocalDate dateOfBirth;
private String address;
private BigDecimal yearlyIncome;
private int accountNumber;
public Person() { }
public Person(String firstName, String lastName, int age, LocalDate dateOfBirth, String address, BigDecimal yearlyIncome, int accountNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.address = address;
this.yearlyIncome = yearlyIncome;
this.accountNumber = accountNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public BigDecimal getYearlyIncome() {
return yearlyIncome;
}
public void setYearlyIncome(BigDecimal yearlyIncome) {
this.yearlyIncome = yearlyIncome;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
}
Ok, next Account
You should read about super() keyword to call methods or constructors from parent class, I used it here just to show you how to do it, you give it to parent and set account class fields
import java.math.BigDecimal;
public class Account extends Person {
private int accountNumber;
private int pin;
private BigDecimal checkingBalance = BigDecimal.ZERO;
private BigDecimal savingBalance = BigDecimal.ZERO;
public Account() { }
public Account(int accountNumber, int pin, BigDecimal checkingBalance, BigDecimal savingBalance){
this.accountNumber = accountNumber;
this.checkingBalance = checkingBalance;
this.savingBalance = savingBalance;
this.pin = pin;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
public void withDraw(BigDecimal withDrawAmount){
this.savingBalance = this.savingBalance.subtract(withDrawAmount);
}
public void deposit(BigDecimal depositAmmount){
this.checkingBalance = this.checkingBalance.subtract(depositAmmount);
}
public void transfer(BigDecimal transferAmount, String fromAccount, String toAccount){
if(fromAccount.equals("Checking") && toAccount.equals("Savings")){
this.checkingBalance = this.checkingBalance.subtract(transferAmount);
this.savingBalance = this.savingBalance.add(transferAmount);
}else if(fromAccount.equals("Savings") && toAccount.equals("Checking")){
this.savingBalance = this.savingBalance.subtract(transferAmount);
this.checkingBalance = this.checkingBalance.add(transferAmount);
}
System.out.print("Your New Checking Balance Is: " + this.checkingBalance);
System.out.print("Your New Savings Balance Is: " + this.savingBalance);
}
public BigDecimal checkBalance(){
return this.checkingBalance.add(this.savingBalance);
}
}
Main
I improve a little Main class, you can see that I use List personsAccount, Collections are dynamic you can add as many elements as you want, means that you use collection of type account, you can do it like List too but read about inheritance and generics first. I add 5th option to back to main menu, also use do while option, 1 list is enough, you don't need persons and accounts arrays.
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final Scanner scanner = new Scanner(System.in);
//if you use java 8 or above you can just do it like = new ArrayList<>();
//static is here just because of example, you should reconsider it
private static final List<Account> personsAccounts = new ArrayList<Account>();
public static void main(String[] args) {
BigDecimal withdrawAmount;
BigDecimal depositAmount;
BigDecimal transferAmount;
int mainChoice;
int choice;
boolean session = true;
Account currentLoggedAccount = new Account();
int loginSuccess = -1;
while (session) {
System.out.println("================================================================================================");
System.out.println("Welcome To The California Bank :)");
System.out.println("1. Login..");
System.out.println("2. Create A New Customer.");
System.out.println("3. Done With Transactions.");
mainChoice = scanner.nextInt();
switch (mainChoice) {
case 1:
System.out.println("Please Enter Your Account Number:");
int accountNumber = scanner.nextInt();
System.out.println("Please Enter Your Pin:");
int pin = scanner.nextInt();
for (int i = 0; i < personsAccounts.size(); i++) {
if (personsAccounts.get(i).getAccountNumber() == accountNumber && personsAccounts.get(i).getPin() == pin) {
System.out.println(personsAccounts.get(i).getAccountNumber());
System.out.println(personsAccounts.get(i).getPin());
System.out.println("Customer Logged In and Validated.");
currentLoggedAccount = personsAccounts.get(i);
loginSuccess = 0;
} else {
System.out.println("Sorry You Are Not A Current Customer!");
loginSuccess = -1;
}
}
if (loginSuccess == 0) {
do {
System.out.println("======================================================================================");
System.out.println("What Else Would You Like To Do Today?");
System.out.println("1. Deposit.");
System.out.println("2. Withdraw.");
System.out.println("3. Transfer Money.");
System.out.println("4. Check Balance.");
System.out.println("5. Back to main menu");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("How Much Money Would You Like To Deposit?");
depositAmount = scanner.nextBigDecimal();
currentLoggedAccount.deposit(depositAmount);
break;
// is case 2 and 3 is the same?
case 2:
System.out.println("How Much Money Would You Like To Withdraw Today?");
withdrawAmount = scanner.nextBigDecimal();
currentLoggedAccount.withDraw(withdrawAmount);
break;
case 3:
System.out.println("How Much Money Would You Like To Withdraw Today?");
transferAmount = scanner.nextBigDecimal();
System.out.println("1. Press 1 To Transfer From Checking to Savings.");
System.out.println("2. Press 2 To Transfer From Savings To Checking.");
int transferChoice;
transferChoice = scanner.nextInt();
if (transferChoice == 1) {
currentLoggedAccount.transfer(transferAmount, "Checking", "Savings");
} else {
currentLoggedAccount.transfer(transferAmount, "Savings", "Checking");
}
break;
case 4:
System.out.println("Here Is Your Total Account Balance");
currentLoggedAccount.checkBalance();
break;
default:
System.out.println("There is no option :(");
break;
}
}
while (choice != 5);
}
break;
case 2:
Account accountToAdd = new Account();
System.out.println("Please Enter Your First Name For The Account Creation:");
scanner.next();
String firstName = scanner.nextLine();
accountToAdd.setFirstName(firstName);
System.out.println("Please Enter Your Last Name For The Account Creation:");
scanner.next();
String lastName = scanner.nextLine();
accountToAdd.setLastName(lastName);
System.out.println("Please Enter Your Age:");
int age = scanner.nextInt();
accountToAdd.setAge(age);
System.out.println("Please Enter Your Date Of Birth:");
String date = scanner.next();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy");
accountToAdd.setDateOfBirth(LocalDate.parse(date, dtf));
System.out.println("Please Enter Your Address:");
scanner.next();
String address = scanner.nextLine();
accountToAdd.setAddress(address);
System.out.println("Please Enter Your Yearly Income:");
BigDecimal annualIncome = scanner.nextBigDecimal();
accountToAdd.setYearlyIncome(annualIncome);
System.out.println("Generating Your Account Number.....");
Random rand = new Random();
//that is some kind of weir because what if somebody have this number yet? :D
int newAccountNumber = rand.nextInt(100000);
accountToAdd.setAccountNumber(newAccountNumber);
System.out.println("Your New Account Number Is: " + newAccountNumber);
System.out.println("Please Enter A 4 Digit Pin");
pin = scanner.nextInt();
accountToAdd.setPin(pin);
//adding new account to list
personsAccounts.add(accountToAdd);
System.out.println("New Customer Created:");
break;
case 3:
System.out.println("Thanks For Using The California Banking System. Goodbye!");
session = false;
break;
default:
System.out.println("There is no option :(");
break;
}
}
}
}
This code isn't perfect but it's working and its clearer, it can be improved by you as you wish. Hope you will learn something, read about java.Collections, java.Time, java Generics, you can also exchange normal for to for each loop like for(Account account : personsAccounts) {}. Cheers!

Problem in reading input from user and writing to a file in Java

This is the base class Employee code
public class Employee {
private String name;
private int age;
private String address;
private String EmpId;
private double salary;
public Employee(String name,int age,String address,String EmpId,double salary) {
this.name=name;
this.age=age;
this.address=address;
this.EmpId=EmpId;
this.salary=salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmpId() {
return EmpId;
}
public void setEmpId(String empId) {
EmpId = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Here Software employee is extending this base class
public class SoftwareEmployee extends Employee{
private String skillSet;
public SoftwareEmployee(String name,int age,String address,String EmpId,double salary,String
skillSet) {
super(name,age,address,EmpId,salary);
this.skillSet=skillSet;
}
public String getSkillSet() {
return skillSet;
}
public void setSkillSet(String skillSet) {
this.skillSet = skillSet;
}
}
Also Finance Employee is extending the base class
the code is :
public class FinanceEmployee extends Employee {
private String Degree;
public FinanceEmployee(String name,int age,String address,String EmpId,double salary,String Degree) {
super(name,age,address,EmpId,salary);
this.Degree=Degree;
}
public String getDegree() {
return Degree;
}
public void setDegree(String degree) {
Degree = degree;
}
}
Here it can't write to an external file. Also console is not waiting for me to insert name first and then age. It is just printing name and age at once and then again two things at the same time. I am very new to this.
This is my main class
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//File file = new File("C:\\Users\\AK078479\\Documents\\newfile.txt");
FileWriter fWriter = new FileWriter("C:\\Users\\AK078479\\Documents\\newfile.txt");
//BufferedWriter writer = null;
Employee employee=new Employee(null, 0, null, null, 0);
SoftwareEmployee sftemp=new SoftwareEmployee(null, 0, null, null, 0, null);
FinanceEmployee fncemp=new FinanceEmployee(null, 0, null, null, 0, null);
System.out.println("You are "+"\n"+"1.Reviewer"+"\n"+"2.Data Entry Operator");
int choice = sc.nextInt();
switch(choice) {
case(1):
System.out.println("Do you want to see a"+ "\n" + "1.Particular record"+"\n"+"2.All
records");
int value=sc.nextInt();
switch(value) {
case(1):
}
break;
case(2):
System.out.println("Employee is a "+"\n"+"1.Software Employee"+"\n"+"2.Finance
Employee");
int num =sc.nextInt();
switch(num) {
case(2):
try {
//String s="Finance Employee";
//writer.write(s);
//writer.newLine();
int n=2;
while(n>0) {
//writer = new BufferedWriter(fWriter);
System.out.println("Enter name");
String text = sc.next();
fncemp.setName(text);
fWriter.write(text);
//fWriter.newLine();
System.out.println("Enter age");
int age=sc.nextInt();
fncemp.setAge(age);
fWriter.write(age);
//writer.newLine();
System.out.println("Enter address");
String add = sc.nextLine();
fncemp.setAddress(add);
fWriter.write(add);
//fwriter.newLine();
System.out.println("Enter EmpId");
String emplId = sc.nextLine();
fncemp.setEmpId(emplId);
fWriter.write(emplId);
//writer.newLine();
System.out.println("Enter salary");
double sal = sc.nextDouble();
fncemp.setSalary(sal);
fWriter.write((int) sal);
//writer.newLine();
System.out.println("Enter degree");
String degree = sc.nextLine();
fncemp.setDegree(degree);
fWriter.write(degree);
//writer.newLine();
n--;
}
} catch (Exception e) {
System.out.println("Error!");
}
break;
case(1):
try {
//String st="Software Employee";
//writer.write(st);
// writer.newLine();
int n=2;
while(n>0) {
//fWriter = new FileWriter(file);
//writer = new BufferedWriter(fWriter);
System.out.println("Enter name");
//String text = sc.nextLine();
sftemp.setName(sc.nextLine());
fWriter.write(sftemp.getName());
//fWriter.newLine();
System.out.println("Enter age");
int age=sc.nextInt();
sftemp.setAge(age);
fWriter.write(age);
//fWriter.newLine();
System.out.println("Enter address");
String add = sc.nextLine();
sftemp.setAddress(add);
fWriter.write(add);
//writer.newLine();
System.out.println("Enter EmpId");
String emplId = sc.nextLine();
sftemp.setEmpId(emplId);
fWriter.write(emplId);
//writer.newLine();
System.out.println("Enter salary");
double sal = sc.nextDouble();
sftemp.setSalary(sal);
fWriter.write((int) sal);
//writer.newLine();
System.out.println("Enter skill Set");
String skill = sc.nextLine();
sftemp.setSkillSet(skill);
fWriter.write(skill);
//writer.newLine();
n--;
}
} catch (Exception e) {
System.out.println("Error!");
}
break;
default:
System.out.println("Try again");
}
break;
default:
System.out.println("Try again");
}
}
}
After you use a scanner method nextInt() you should call nextLine() one more time before you can read a string. The reason for that is that after you call nextInt the scanner internal cursor which tracks your position in the input stream passes the integer number, but stops right in front of the new line character. When you call nextLine() the scanner will just return the empty string and move to the next line, so only the next nextLine() call will return non-empty string which you entered after the number. Thus, for example here:
System.out.println("You are "+"\n"+"1.Reviewer"+"\n"+"2.Data Entry Operator");
int choice = sc.nextInt();
switch(choice)
you need to add:
System.out.println("You are "+"\n"+"1.Reviewer"+"\n"+"2.Data Entry Operator");
int choice = sc.nextInt();
sc.nextLine(); // Skip the end of line and prepare to read something from the next line
switch(choice)

Java issues with console menu

I have created a functioning console menu and I will choose an option to add a new customer, as you can see below I have created the scanner to enter the details, what I dont know is how I would save the user input out to a text file called CustomerInformation. I can either do this with a function on this method or if there is some way to store the information and create a save function before I quit out of the console menu.
public void addCustomer()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
this.name = sc.nextLine();
System.out.print("Enter Address: ");
this.address = sc.nextLine();
System.out.print("Enter Gender(M or F): ");
this.gender = sc.nextLine();
System.out.print("Enter Date of Birth: ");
this.dob = sc.nextLine();
}
the whole customer class is:
import java.util.*;
import java.io.*;
public class Customer {
private String name;
private String address;
private String gender;
private String dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
Customer (){
setName("Name");
setAddress("Address");
setGender("Gender");
setDob("dDob");
}
Customer (String strName, String strAddress, String strGender, String strDob, String strReport){
setName(strName);
setAddress(strName);
setGender(strGender);
setDob(strDob);
}
//Add Customer Function-------------------------------------------------------------------
public void addCustomer()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
this.name = sc.nextLine();
System.out.print("Enter Address: ");
this.address = sc.nextLine();
System.out.print("Enter Gender(M or F): ");
this.gender = sc.nextLine();
System.out.print("Enter Date of Birth: ");
this.dob = sc.nextLine();
}
//End Add Customer-------------------------------------------------------------------------
//Search Function-------------------------------------------------------------------------
//End Search Function-------------------------------------------------------------------
//Delete Customer Function ------------------------------------------------------
//End Delete Customer Function---------------------------------------------------------
//Save Progress Function--------------------------------------------------------------
//End Save Progress Function----------------------------------------------------------
public static int nextInt()
{
Scanner keyb = new Scanner(System.in);
int i = keyb.nextInt();
return i;
}
}
This is Test class.read writeCustomerToFile method.this is not difficult.i hope you will figure out:
public final class Test {
public static void main(String[] args) {
Customer customer = new Customer();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
customer.setName(sc.nextLine());
System.out.print("Enter Address: ");
customer.setAddress(sc.nextLine());
System.out.print("Enter Gender(M or F): ");
customer.setGender(sc.nextLine());
System.out.print("Enter Date of Birth: ");
customer.setDob(sc.nextLine());
writeCustomerToFile(customer,"D:/yourfilename.txt");
}
public static void writeCustomerToFile(Customer customer, String fileName) {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
writer.println("name:" + customer.getName());
writer.println("address:" + customer.getAddress());
writer.println("gender:" + customer.getGender());
writer.println("birth date:" + customer.getDob());
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
writer.close();
}
}
}
Your customer class is the same not changed

How do you retrieve all of the records that a user inputs into an arraylist in java

I am trying to retrieve every record that an arraylist contains. I have a class called ContactList which is the super class of another class called BusinessContacts. My first task is to print only the first name and last name of a contact. The second task is to print details of a contact that's related to its id number. The ContactList class has all the instance variables and the set/get methods and the toString() method. The BusinessContact class consists of only two instance variables that need to be appended to the ContactList class. How is can this be worked out? The code is below:
The ContactList class:
package newcontactapp;
public abstract class ContactList {
private int iD;
private String firstName;
private String lastName;
private String adDress;
private String phoneNumber;
private String emailAddress;
// six-argument constructor
public ContactList(int id, String first, String last, String address, String phone, String email) {
iD = id;
firstName = first;
lastName = last;
adDress = address;
phoneNumber = phone;
emailAddress = email;
}
public ContactList(){
}
public void displayMessage()
{
System.out.println("Welcome to the Contact Application!");
System.out.println();
}
public void displayMessageType(String type)
{
System.out.println("This is a " + type);
System.out.println();
}
public int getiD() {
return iD;
}
public void setiD(int id) {
iD = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String first) {
firstName = first;
}
public String getLastName() {
return lastName;
}
public void setLastName(String last) {
lastName = last;
}
public String getAdDress() {
return adDress;
}
public void setAdDress(String address) {
adDress = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phone) {
phoneNumber = phone;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String email) {
emailAddress = email;
}
public String toString(){
return getiD() + " " + getFirstName() + " " + getLastName() + " " + getAdDress() + " " + getPhoneNumber() + " " + getEmailAddress() + "\n" ;
}
}
The BusinessContacts class:
package newcontactapp;
public class BusinessContacts extends ContactList {
private String jobTitle;
private String orGanization;
//
public BusinessContacts(int id, String first, String last, String address, String phone, String email, String job, String organization){
super();
jobTitle = job;
orGanization = organization;
}
public BusinessContacts(){
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String job) {
jobTitle = job;
}
public String getOrGanization() {
return orGanization;
}
public void setOrGanization(String organization) {
orGanization = organization;
}
//#Override
public String toString(){
return super.toString()+ " " + getJobTitle()+ " " + getOrGanization() + "\n";
}
}
Here is my main method class:
package newcontactapp;
import java.util.ArrayList;
//import java.util.Iterator;
import java.util.Scanner;
public class NewContactAppTest {
//ArrayList<ContactList> fullList = new ArrayList<>();
ArrayList<ContactList> bContacts = new ArrayList<>();
ArrayList<ContactList> pContacts = new ArrayList<>();
public static void main(String [] args)
{
ContactList myContactList = new ContactList() {};
myContactList.displayMessage();
new NewContactAppTest().go();
}
public void go()
{
ContactList myContactList = new ContactList() {};
System.out.println("Menu for inputting a Business Contact or Personal Contact");
System.out.println();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a numeric choice below: ");
System.out.println();
System.out.println("1. Add a Business Contact");
System.out.println("2. Add a Personal Contact");
System.out.println("3. Display Contacts");
System.out.println("4. Quit");
System.out.println();
String choice = input.nextLine();
if(choice.contains("1")){
String type1 = "Business Contact";
myContactList.displayMessageType(type1);
businessInputs();
}
else if(choice.contains("2")){
String type2 = "Personal Contact";
myContactList.displayMessageType(type2);
personalInputs();
}
else if(choice.contains("3")) {
displayContacts();
displayRecord();
}
else if(choice.contains("4")){
endOfProgram();
}
}
public void businessInputs()
{
BusinessContacts myBcontacts = new BusinessContacts();
//ContactList myContactList = new ContactList() {};
//ContactList nameContacts = new ContactList() {};
bContacts.clear();
int id = 0;
myBcontacts.setiD(id);
Scanner in = new Scanner(System.in);
while(true){
id = id + 1;
myBcontacts.setiD(id);
//myContactList.setiD(id);
System.out.println("Enter first name ");
String firstName = in.nextLine();
//nameContacts.setFirstName(firstName);
//myContactList.setFirstName(firstName);
myBcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
//nameContacts.setLastName(lastName);
//myContactList.setLastName(lastName);
myBcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
//myContactList.setAdDress(address);
myBcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
//myContactList.setPhoneNumber(phoneNumber);
myBcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
//myContactList.setEmailAddress(emailAddress);
myBcontacts.setEmailAddress(emailAddress);
System.out.println("Enter job title: ");
String jobTitle = in.nextLine();
myBcontacts.setJobTitle(jobTitle);
System.out.println("Enter organization: ");
String organization = in.nextLine();
myBcontacts.setOrGanization(organization);
//bContacts.add(myContactList);
bContacts.add(myBcontacts);
//names.add(nameContacts);
//System.out.println("as entered:\n" + bContacts);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
continue;
}
else{
break;
}
}
//bContacts.add(myBcontacts);
go();
}
public void personalInputs(){
ContactList myContactList = new ContactList() {};
PersonalContacts myPcontacts = new PersonalContacts();
Scanner in = new Scanner(System.in);
int id;
id = 1;
while(true){
System.out.println("Enter first name; ");
String firstName = in.nextLine();
myContactList.setFirstName(firstName);
myPcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
myContactList.setLastName(lastName);
myPcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
myContactList.setAdDress(address);
myPcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
myContactList.setPhoneNumber(phoneNumber);
myPcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
myContactList.setEmailAddress(emailAddress);
myPcontacts.setEmailAddress(emailAddress);
System.out.println("Enter birth date");
String dateOfBirth = in.nextLine();
myPcontacts.setDateOfBirth(dateOfBirth);
//pContacts.add(myContactList);
pContacts.add(myPcontacts);
id = id + 1;
myContactList.setiD(id);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if (choice.equalsIgnoreCase("y")) {
continue;
}
else{
break;
}
}
go();
}
public void displayContacts(){
System.out.println();
for(ContactList name : bContacts){
System.out.println(name.getiD() + " " + name.getFirstName()+ " " + name.getLastName());
}
}
public void displayRecord(){
System.out.println();
System.out.println("Do you wish to see details of contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
System.out.println();
System.out.println("Enter the numeric key from the list to see more specific details of that record");
System.out.println();
Scanner key = new Scanner(System.in);
System.out.println();
ContactList record = new ContactList() {};
for(int i = 0; i < bContacts.size(); i++){
record = bContacts.get(i);
System.out.println(record.toString());
}
}
else{
go();
}
/* else{
System.out.println();
System.out.println("This is a Personal Contact");
System.out.println();
for(int j = 0; j < pContacts.size(); j++){
ContactList pList = pContacts.get(j);
pList = pContacts.get(j);
System.out.println(pList.toString());
}
}*/
}
public void endOfProgram(){
System.out.println("Thank you! Have a great day!");
Runtime.getRuntime().exit(0);
}
}
If you're looking to get a value based on ID, try making a method that iterates over the contents of the ArrayList to find one that matches:
public ContactList getContactList(int id) {
for (ContactList list : /*your ContactList List object*/) {
if (list.getiD() == id) {
return list;
}
}
return null;
}
This will return null if none is found, or the first result in the list.

How to add valid input into arraylist?

This is my ID program which stores first name, last name, date and place on birth, email and phone number. How do I make and store a person object with only valid birth date, email and phone number (instead of having all the attributes)?
This is my main ID program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ID {
static List<Oseba> id = new ArrayList<Oseba>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
int choice = 0;
boolean isDate = false;
String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
System.out.println("How many IDs would you like to enter? ");
max = sc.nextInt();
System.out.println(" 0. Exit. ");
System.out.println(" 1. Add contact. ");
System.out.println(" 2. Outprint all contacts. ");
choice = sc.nextInt();
while (choice != 0) {
switch (choice) {
case 0:
System.out.println("Goodbye!");
System.exit(0);
case 1:
while (choice != 2) {
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter date of birth (dd-mm-yyyy): ");
String date = sc.next();
isDate = date.matches(regEx_Date);
System.out.println("Enter place of birth: ");
String place = sc.next();
System.out.println("Enter email: ");
String email = sc.next();
Pattern p = Pattern.compile(regEx_Email);
Matcher m = p.matcher(email);
if (m.find()) {
System.out.println(email + " is a valid email address.");
} else {
System.out.println(email + " is a invalid email address");
}
System.out.println("Enter phone number:");
String phone = sc.next();
addID(firstName, lastName, date, place, email, phone);
}
break;
case 2:
System.out.println("\n" + ID.id);
break;
default:
System.out.println("Try again.");
break;
}
System.out.println(" 0. Exit. ");
System.out.println(" 1. Add contact. ");
System.out.println(" 2. Outprint all contacts. ");
choice = sc.nextInt();
}
}
private static void addID(String firstName, String lastName, String date, String place, String email, String phone) {
Person p = new Person(firstName, lastName, date, place, email, phone);
id.add(p);
}
}
And my Person class:
class Person {
String firstName;
String lastName;
String date;
String place;
String email;
String phone;
public Person(String firstName, String lastName, String date, String place, String email, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.date = date;
this.place = place;
this.email = email;
this.phone = phone;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "First Name: " + firstName + "\n"
+ "Last Name: " + lastName + "\n"
+ "Date of birth: " + date + "\n"
+ "Place of birth: " + place + "\n"
+ "Email: " + email + "\n"
+ "Phone number: " + phone + "\n\n";
}
}
Thanks for the help.
The best approach would be to break down your problem into smaller ones. For example, in order to validate the input, what you will have to do, instead of calling the setter directly is to create a method that will be responsible to validate the input for every single case. Try to use this approach everywhere since low coupling and high cohesion is always a requirement! I will provide an example on your implementation, however, there are multiple ways to do that. Also I wont use exceptions since I noticed that you are still in the beginning.
Apart from that, in order for this to work, you should add a default constructor(the values are predifined) in the Person Class.
Finally, eventhough the approach with multiple while loops is not recommented because it makes the code more complicated, I used it in order to demonstrate you how you can make sure that you will get the correct input, for example if the user input doesnt get validated, then the program will continue to ask the user until it will get the correct input. Additionally, when the user makes a mistake, directions should be provided in order to guide him/her. (this is normally done with exceptions, in our case though we provide this with simple console prints).
So let's see:
public class ID {
static List<Oseba> id = new ArrayList<Oseba>();
\*we create the menu like that in order to avoid multiple lines repetitions *\
private static String menuOptions = "Menu:" + "\nExit - Insert 0"
+ "\nAdd contact - Insert 1" + "\nExit Outprint all contacts - Insert 2";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
int choice = 0;
boolean isDate = false;
System.out.println("How many IDs would you like to enter? ");
max = sc.nextInt();
Person p = new Person();
while (true) {
print(menuOptions);
choice = sc.nextInt();
switch (choice) {
case 0:
System.out.println("Goodbye!");
System.exit(0);
case 1:
while(true){
String fname = getString("Enter First Name: ");
if(verifyName(fname)){
p.setFirstName(fname);
break;
}
}
while(true){
String lname = getString("Enter Last Name: ");
if(verifyName(lname)){
p.setLastName(lname);
break;
}
}
while(true){
String date = getString("Enter date of birth (dd-mm-yyyy): ");
if(verifyBirthDate(date)){
p.setDate(date);
break;
}
}
while(true){
String birthPlace = getString("Enter place of birth: ");
if(verifyBirthPlace(birthPlace)){
p.setPlace(birthPlace);
break;
}
}
while(true){
String email = getString("Enter email address: ");
if(verifyEmail(email)){
p.setEmail(email);
break;
}
}
while(true){
String phoneNumber = getString("Enter phone number: ");
if(verifyPhoneNumber(phoneNumber)){
p.setPhone(phoneNumber);
break;
}
}
addID(p);
break;
case 2:
System.out.println("\n" + ID.id);
break;
default:
System.out.println("Try again.");
break;
}
print(menuOptions);
choice = sc.nextInt();
}
}
private static void addID(Person prs) {
id.add(prs);
}
public static Boolean verifyName(String name) {
if(!name.matches("[a-zA-Z]+")){
print("\nERROR_MESSAGE:____________The first/last name should contain only letters, everything else is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyBirthDate(String date) {
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
if(!date.matches(regEx_Date)){
print("\nERROR_MESSAGE:____________The birth date is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyBirthPlace(String birthPlace) {
if(!birthPlace.matches("[a-zA-Z]+")){
print("\nERROR_MESSAGE:____________The birth place is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyEmail(String email) {
String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern p = Pattern.compile(regEx_Email);
Matcher m = p.matcher(email);
if(!m.find()){
print("\nERROR_MESSAGE:____________"+email+" is an invalid email address");
return false;
}else{
return true;
}
}
public static Boolean verifyPhoneNumber(String phoneNumber) {
if(!phoneNumber.matches("[0-9]+")){
print("\nERROR_MESSAGE:____________The phone No. should contain only numbers, everything else is not valid!");
return false;
}else{
return true;
}
}
public static String getString(String msg) {
Scanner in = new Scanner(System.in);
print(msg);
String s = in.nextLine();
return s;
}
public static void print(String s) {
System.out.println(s);
}
}
Create a constructor like this
public Person(String date, String email, String phone) {
this.date = date;
this.email = email;
this.phone = phone;
}
You could optionally add
this.firstName = null;
this.lastName = null;
//for all of your fields.
You also need to uodate your getters and toString method to check if the field has been initialized. For example, for your getFirstName()
if (firstName!=null)
return firstName;
return "";
May better name for isDate field is isValidDate.
Can you use simple if statement:
if(isValidDate && m.find())
addID(firstName, lastName, date, place, email, phone);
Or can you create method for checking validation:
private boolean isValidDate(String date){
if(number!=null && number!=""){
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
return date.matches(regEx_Date);
}
return false;
}
Have you ever heard about Primitive Obsession?
I would use a Date (JodaDate) instead of String for birth date.
I would create an Email value object, throwing an IllegalArgumentException if the String provided isn't a valid email (validated by regexp).
I would create a Phone value object, throwing an IllegalArgumentException if the String provided isn't a valid phone number.
The constructor becoming:
public Person(String firstName, String lastName, Date birthDate, String place, Email email, Phone phone)
For instance, the Email object would be:
public class Email {
private String value;
public Email(String email) {
if(isNotValid(email))
throw new IllegalArgumentException("Your mail is not valid!");
this.value = email;
}
public final String getValue(){
return email;
}
private boolean isNotValid(){
//return false if email regexp validation is not verified
}
//....equals - hashcode if needed here
}
Thus, your Person would always be a valid person.
Indeed, checking that its components are valid is then the responsibility of the client, not the Person directly. It's more informative for the reader what a Person expects, just by reading the API.
Add a new boolean variable to keep track valid inputs. If all inputs are valid then only add Person object to ArrayList
boolean isValid=true;
if (m.find()) {
System.out.println(email + " is a valid email address.");
} else {
isValid=false;
System.out.println(email + " is a invalid email address");
}
if(isValid)
{
//Do other check phone number and valid birth date similarly
}
if(isValid)
{
addID(firstName, lastName, date, place, email, phone);
}

Categories

Resources