I am trying to print out the results of the users inputs to a simple text file but everything I have tried has rendered unsuccessful. I tried using a PrintWriter within the switch case but the results still just printed out null. I am quite new to Java so maybe I am missing obvious?
Here is the code:
package parkingsystem;
import java.io.*;
import java.util.Scanner;
public class Registration {
static String [][] userData;
static String [][] fileData;
public static void Registration(){
Scanner input = new Scanner(System.in);
String lotNo;
String First;
String Last;
String studentID;
String phoneNo;
String email;
String carNo;
String dateReg;
String strcontent;
String proceed;
boolean proceed2 = true;
userData = new String [50][6];
fileData = new String [50][6];
int counter = 0;
int col;
int row;
boolean carry_on = true;
MainMenu choices = new MainMenu();
while(proceed2=true){
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
proceed = input.nextLine();
switch (proceed) {
case "Y":
case "y":
System.out.println("Enter your student ID");
studentID = input.nextLine();
System.out.println("Enter your first name");
First = input.nextLine();
System.out.println("Enter your last name");
Last = input.nextLine();
System.out.println("Enter your car number");
carNo = input.nextLine();
System.out.println("Enter your contact number");
phoneNo = input.nextLine();
System.out.println("Enter your email address");
email = input.nextLine();
row = counter ;
userData [row][0] = studentID;
userData [row][1] = First;
userData [row][2] = Last;
userData [row][3] = carNo;
userData [row][4] = phoneNo;
userData [row][5] = email;
if (counter == 6){
carry_on=false;
}
proceed2 = false;
break;
case "N":
case "n":
choices.Menus();
break;
}
}
}
}
Here's a second pass at re-factoring your code.
So now in this refactoring we capture and store the newly created CarOwner objects and store them in a list.
Then we see how to go through that List of CarOwner's and then write those objects to a file called carOwners.dat
Ordinarily, in industry, code re-factoring is done in the context of having a set of unit tests against which you can ensure that the refactoring hasn't broken the required behaviour of the code but we are just learning here so this work serves to explain some of the concepts that you are missing and this first pass iteration below has some issues of its own so don't take this as the final product.
Refactorings
I have created a CarOwner class.
I have renamed the Boolean variable canProceed so that it reads more naturally.
Update : I have made the CarOwner class Serializable; this will allow us to write the Object to a File.
Update : I have added code that up the new CarOwners and adds it to a List and then I iterate over the list to write those CarOwner objects to a FileStream.
package parkingsystem;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.FileOutputStream;
import java.util.Scanner;
public class Registration {
public static void main(String[] args) {
List carOwners = new ArrayList();
Scanner input = new Scanner(System.in);
boolean canProceed = true;
while (canProceed) {
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
String optionRequested = input.nextLine();
if (optionRequested.equalsIgnoreCase("Y")) {
CarOwner owner = new CarOwner();
System.out.println("Enter your student ID");
owner.setStudentID(input.nextLine());
System.out.println("Enter your first name");
owner.setFirst(input.nextLine());
System.out.println("Enter your last name");
owner.setLast(input.nextLine());
System.out.println("Enter your car number");
owner.setCarNo(input.nextLine());
System.out.println("Enter your contact number");
owner.setContactNumber(input.nextLine());
System.out.println("Enter your email address");
owner.setEmail(input.nextLine());
owner.setDateReg(new Date().toString());
carOwners.add(owner);
} else if (optionRequested.equals("N") || optionRequested.equals("n")) {
canProceed = false;
}
}
ObjectOutputStream objectWriter = null;
for (CarOwner carOwner : carOwners) {
try {
objectWriter = new ObjectOutputStream(new FileOutputStream("carOwners.dat"));
objectWriter.writeObject(carOwner);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here's what the CarOwner class now looks like ...
package parkingsystem;
import java.io.Serializable;
public class CarOwner implements Serializable{
private String First;
private String Last;
private String studentID;
private String email;
private String carNo;
private String dateReg;
private String contactNumber;
public CarOwner() {
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getLast() {
return Last;
}
public void setLast(String last) {
Last = last;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCarNo() {
return carNo;
}
public void setCarNo(String carNo) {
this.carNo = carNo;
}
public String getDateReg() {
return dateReg;
}
public void setDateReg(String dateReg) {
this.dateReg = dateReg;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactNumber() {
return contactNumber;
}
#Override
public String toString() {
return "CarOwner{" +
"First='" + First + '\'' +
", Last='" + Last + '\'' +
", studentID='" + studentID + '\'' +
", email='" + email + '\'' +
", carNo='" + carNo + '\'' +
", dateReg='" + dateReg + '\'' +
", contactNumber='" + contactNumber + '\'' +
'}';
}
}
Ok so creating the CarOwner class is done to make a start at making this code more object oriented.
Secondly the re-factored code demonstrates correct use of a Boolean variable in Java.
As the other commentators have already pointed out the assignment operator = is easily confused with the test for Boolean equality. See Java Operators
Also I have renamed Boolean proceed; to be Boolean canProceed; This is a common strategy. Naming a Boolean variable to read as a question to which the "answer" is, yes or no, or True or False.
This then means we can write code like while(canProceed) which reads very easily. See also if statement on the Java tutorial
I hope this helps.
Related
how would I create a do-while loop to verify that the user input contains no special characters. If it does contain special characters, how would I make it restart the loop? In my loop, it still returns the name if it has special characters.
Here is my main:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInterface user = new UserInterface();
System.out.print("Enter first and last name: ");
String userName = input.nextLine();
user.setName(userName);
user.getName();
}
}
Here is my User class:
import java.util.Random;
public class UserInterface {
Random random = new Random();
private String name;
public String getName() {
String specialCharacters = "!#$%&'()*+,-./:;<=>?#[]^_`{|}123456789";
boolean invalidInput = false;
do {
invalidInput = false;
System.out.print("User: " + name + " ID #" + getUserID());
} while(name.contains(specialCharacters));
invalidInput = false;
return name;
}
public void setName(String userName) {
this.name = userName;
}
public int getUserID() {
return random.nextInt(1000);
}
}
use do while loop to verify weather the user name is valid or not.
For validating use:
public static boolean isValidName(String name){
for(char ch : name.toCharArray())
if(!Character.isLetterOrDigit(ch))
return false;
return name.length() != 0;
}
For getting name:
public static String inputName() {
boolean invalidInput = false;
Scanner scan = new Scanner(System.in);
String name = null;
do {
System.out.print("Enter Name : ");
name = scan.nextLine();
//System.out.println("name " +name);
//System.out.print("User: " + name + " ID #" + getUserID());
} while(!isValidName(name));
return name;
}
Main.java
import java.util.Random;
import java.util.Scanner;
class UserInterface {
Random random = new Random();
private String name;
public void setName(String userName) {
this.name = userName;
}
public String getName(){
return name;
}
public int getUserID() {
return random.nextInt(1000);
}
}
public class Main {
public static String inputName() {
boolean invalidInput = false;
Scanner scan = new Scanner(System.in);
String name = null;
do {
System.out.print("Enter Name : ");
name = scan.nextLine();
//System.out.println("name " +name);
//System.out.print("User: " + name + " ID #" + getUserID());
} while(!isValidName(name));
return name;
}
public static boolean isValidName(String name){
for(char ch : name.toCharArray())
if(!Character.isLetterOrDigit(ch))
return false;
return name.length() != 0;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInterface user = new UserInterface();
user.setName(inputName());
System.out.println(user.getName());
}
}
Output:
$ javac Main.java && java Main
Enter Name : Dev Par
Enter Name : DevPar
DevPar
I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.
import entidades.*;
public class Main {
public static void main(String[] args) {
Profissional prof = new Profissional(null, null);
List<Profissional> profissional = new ArrayList<Profissional>();
Scanner sc = new Scanner(System.in);
boolean loop = true;
while(loop == true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.nextLine();
String categoriaPro = sc.nextLine();
prof.NomeVerificacao(profissional, nomePro, categoriaPro);
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissional) {
System.out.println(pro);
This is my Main, it's running fine but i don´t think it is adding the atributes to the list and not verifying either.
i want to add the atributes to a list so i can create different objets but they can not have at least the name equal.
public class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
public void NomeVerificacao(List<Profissional> profissional ,String nome, String categoria) {
if(profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
}else {
for(Profissional pro : profissional) {
if(pro.nome.contentEquals(nome)) {
System.out.println("Já Exite esse nome");
}else {
profissional.add(new Profissional(nome, categoria));
}
}
}
}
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
this is the Profissional Class.
I'm almost there i think but the output keeps saying that the name exists even though it is the first name i'm inserting.
I ran your code on my machine and made 3 changes into it, and it's working for me now,
1)
String nomePro = sc.next();
String categoriaPro = sc.next();
2) In professional class just changed this function a bit:
public void NomeVerificacao(List<Profissional> profissional, String nome, String categoria) {
if (profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
} else {
int i = 0;
for (; i < profissional.size(); i++) {
if (profissional.get(i).nome.equals(nome)) {
System.out.println("Já Exite esse nome");
break;
}
}
if (i == profissional.size()) {
profissional.add(new Profissional(nome, categoria));
}
}
}
3) At the end of the class Main, wrote sc.close(); to close the scanner.
i/p and o/p :
1) RP
red
color
2) RP
orange
color
3) RP
orange
paint
Já Exite esse nome
4) SAIR
nome=red, categoria=color
nome=orange, categoria=color
As you can see in above i/p and o/p, nome=red and nome=orange with categoria=color are added in the list but when we tried to add the same nome=orange again but with different category as paint it didn't add it and printed the message "Já Exite esse nome".
and after entering SAIR, the toString(); printed the list content at the end. So the message will be printed only if we try to add the object with the same name again int list (not the first or any other times).
Further optimizations are possible but for now, it will work!
I can propose the following solution:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Set is a data structure that makes sure you don't have a duplicated elements
// in this case we use TreeSet structure that accepts comparator which tells that
// we need to compare elements only by professional's name
Set<Profissional> profissionals = new TreeSet<>(Comparator.comparing(Profissional::getNome));
while (true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.next();
String categoriaPro = sc.next();
// add function returns true in case the element we're going to add
// was not presented in Set structure yet. False otherwise.
boolean isNew = profissionals.add(new Profissional(nomePro, categoriaPro));
if (!isNew) {
System.out.println("Professional with name " + nomePro + " already exists");
} else {
System.out.println("Professional with name " + nomePro + " was added");
}
} else if (comando.contentEquals("SAIR")) {
break;
}
}
// just prints all professionals at the end of the program
profissionals.forEach(System.out::println);
}
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
// getters and setters
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
The output will be the following:
RP
test test
Professional with name test was added
RP
test1 test1
Professional with name test1 was added
RP
test test3
Professional with name test already exists
SAIR
nome=test, categoria=test
nome=test1, categoria=test1
package javaapplication8;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JavaApplication8 {
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
}
public static void main(String[] args) {
try {
List<Profissional> profissionalList= new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("\r\nEnter comando:");
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
System.out.print("nome: ");
String nome = sc.next();
sc.nextLine(); // wait enter
System.out.print("categoria: ");
String categoria = sc.next();
sc.nextLine(); // wait enter
// access constructor of Profissional
Constructor profCtor = Profissional.class.getConstructor(String.class, String.class);
profCtor.setAccessible(true);
// create instance of Profissional
Profissional newItem = (Profissional) profCtor.newInstance(nome, categoria);
// avoid duplicate nome in profissionalList
boolean isExist = false;
for(Profissional pro : profissionalList) {
if(pro != null){
if(pro.nome.toLowerCase().equals(newItem.nome.toLowerCase())){
isExist = true;
break;
}
}
}
if(!isExist){
profissionalList.add(newItem );
}
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissionalList) {
if(pro != null) {
System.out.println("nome: " + pro.nome + " categoria: " + pro.categoria);
}
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
I have managed to put all objects into arraylist but I am not able to print all values. Only the last one is getting printed, regardless of method used.
It is not getting printed through ArrayList only, which makes me wonder if the objects pushed are the same.
If it is, how do I change that? I have attached the program (run FileInput.java):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.swing.text.html.HTMLDocument.Iterator;
//lecture notes(L1) method
public class FileInput {
static String first;
static String second;
static String third;
static String fourth;
static String fifth;
static String sixth;
static int num = 1;
public static void main(String[] args)throws FileNotFoundException, IOException{
Scanner input = new Scanner(new File("player.txt"));
String data = null;
PrintWriter output = new PrintWriter("outfile.txt");
// Player1 user = new Player1();
ArrayList<Player1>listOfPlayers = new ArrayList<>();
Player1 user = new Player1();
// Tokenizing
System.out.println("CSCI213 Players Management System");
while(input.hasNextLine()){
System.out.println("\nPlayer " + num);
data = input.nextLine();
StringTokenizer token = new StringTokenizer(data,"|");
// int t = token.countTokens();
// System.out.println("t is:" + t);
first = token.nextToken().trim();
user.setLoginname(first);
second = new String(token.nextToken("|"));
user.setPassword(second);
third = new String(token.nextToken("|"));
user.setChips(third);
fourth = new String(token.nextToken("|"));
user.setUsername(fourth);
fifth = new String(token.nextToken("|"));
user.setEmail(fifth);
sixth = new String(token.nextToken("|"));
user.setBirthdate(sixth);
// user.display();
listOfPlayers.add(user);
System.out.println("Size is: " + listOfPlayers.size());
// System.out.println(user.loginname);
// System.out.println(listOfPlayers.get(num-1).loginname);
num++;
// output.write(data);
// output.write("\r\n");
}
int x = listOfPlayers.size();
System.out.println("Size is: " + x);
System.out.println(listOfPlayers);
// Display address of required
Player1 p = new Player1();
for(int i = 0; i < x; i++){
p = listOfPlayers.get(i);
System.out.println(p.loginname);
}
for(Player1 e:listOfPlayers){
System.out.println(e.loginname);
System.out.println(e.email);
}
while(input.hasNextLine()){
data = input.nextLine();
output.write(data);
output.write("\r\n");
}
input.close();
output.close();
}
}
// Store all player information
public class Player1 {
static String loginname;
static String password;
static String chips;
static String username;
static String email;
static String birthdate;
/*
public Player1(String loginname, String password,
String username, String email, String birthdate){
this.loginname = loginname;
this.password = password;
this.username = username;
this.email = email;
this.birthdate = birthdate;
}
*/
public Player1() {
// TODO Auto-generated constructor stub
}
public static String getLoginname() {
System.out.print("loginname: ");
return loginname;
}
public static void setLoginname(String loginname) {
Player1.loginname = loginname;
}
public static String getPassword() {
System.out.print("password: ");
return password;
}
public static void setPassword(String password) {
Player1.password = password;
}
public static String getUsername() {
System.out.print("username: ");
return username;
}
public static void setUsername(String username) {
Player1.username = username;
}
public static String getEmail() {
System.out.print("email: ");
return email;
}
public static void setEmail(String email) {
Player1.email = email;
}
public static String getBirthdate() {
System.out.print("birthdate: ");
return birthdate;
}
public static void setBirthdate(String birthdate) {
Player1.birthdate = birthdate;
}
public static String getChips() {
System.out.print("chips: ");
return chips;
}
public static void setChips(String chips) {
Player1.chips = chips;
}
public void display() {
System.out.println("Name: " + this.username);
System.out.println("Email: " + this.email);
System.out.println("Birthdate: " + this.birthdate);
System.out.println("Login ID: " + this.loginname);
System.out.println("Balance Chips: " + this.chips);
}
/*
#Override
public String toString() {
return "toString()=" + this.loginname + "\n";
}
*/
}
Simple:
Player1 user = new Player1();
You are adding the same object again and again. Put that statement into your loop instead. You want to add a completely new Playwer object during each loop iteration!
But even then, things wouldn't work out; because (as Eran figured): your Player class has only static fields. That is like "cheating"; because it means that all Player objects would see the same fields, too (because static fields are shared between all instances of a class!)
In other words: static is an abnormality in good OO design. You don't use it as default; to the contrary: you only make fields static in special corner cases (see here for some examples).
You have two errors :
You are adding the same Player1 instance to the list over and over again. You should move Player1 user = new Player1(); into the loop that adds the players.
Change
Player1 user = new Player1();
// Tokenizing
System.out.println("CSCI213 Players Management System");
while (input.hasNextLine()) {
to
// Tokenizing
System.out.println("CSCI213 Players Management System");
while (input.hasNextLine()) {
Player1 user = new Player1();
The members of the Player1 class are all static, so even if you fix the first issue, all instances of Player1 will share these members. You should change them to non static.
Change
public class Player1 {
static String loginname;
static String password;
static String chips;
static String username;
static String email;
static String birthdate;
to
public class Player1 {
String loginname;
String password;
String chips;
String username;
String email;
String birthdate;
In the driver, it correctly finds the position, but I tried using contacts.remove(foundPosition) ... And the 'Contact' was not deleted.
How can I delete the entire 'Contact' That the user searched for?
Driver:
import java.util.Collections;
import java.util.ArrayList;
import java.util.Scanner;
public class contactDriver
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
// Asks you to enter values from the given menu.
int answer;
System.out.println ("Press 1 to add a contact."); // Menu is printed.
System.out.println ("Press 2 to display all contacts.");
System.out.println ("Press 3 to search for a contact.");
System.out.println ("Press 4 to search for a contact to delete.");
answer = scan.nextInt();
// ArrayList
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("Patrick", "McGee", "334-555-8860", "pmcgee123#gmail.com"));
contacts.add(new Contact("John", "Appleseed", "142-555-6740", "jappleseed99#gmail.com"));
contacts.add(new Contact("Matt", "Jordan", "213-555-2323", "mjordan23#gmail.com"));
contacts.add(new Contact("Kanye", "East", "255-434-9909", "keast123#gmail.com"));
contacts.add(new Contact("Derrick", "Flower", "144-555-1111", "dflower1#gmail.com"));
// If statements for the user's decision.
if (answer == 4){ // User searches for a contact and chooses whether or not to delete the contact.
System.out.println("Enter the first name of the contact to search for.");
String fname = scan.next();
scan.nextLine();
System.out.println("Enter the last name of the contact to search for.");
String lname = scan.next();
scan.nextLine();
Collections.sort(contacts);
for(Contact c : contacts)
System.out.println(c);
int foundPosition = Collections.binarySearch(contacts, new Contact(fname, lname, "", ""));
System.out.println(foundPosition);
// The found contact may or may not be deleted.
String answer2;
System.out.println("Would you like to delete this contact? (y/n)");
answer2 = scan.next();
if (answer2 == "y"){
contacts.remove(foundPosition); // **HERE is where I need help.**
System.out.println ("Contact is deleted. Here is the updated contact list: ");
for(Contact c : contacts)
System.out.println(c);
}
if (answer2 == "n"){
System.out.println("Contact will not be deleted.");
}
}
}
}
Class containing methods:
import java.util.Collections;
import java.util.ArrayList;
import java.util.Comparator;
public class Contact implements Comparable<Contact>
{
public Contact(String fname, String lname, String num, String email)
{
this.fname = fname;
this.lname = lname;
this.num = num;
this.email = email;
}
public String getFirstname()
{
return fname;
}
public String getLastname()
{
return lname;
}
public String getNum()
{
return num;
}
public String getEmail()
{
return email;
}
public int compareTo(Contact other)
{
if (fname.compareTo(other.lname) == 0)
return fname.compareTo(other.fname);
return lname.compareTo(other.lname);
}
public String toString()
{
return "Contact[" + fname + ", " + lname + ", " + num + ", " + email + "]";
}
private String fname;
private String lname;
private String num;
private String email;
}
Comparator:
import java.util.Comparator;
class ContactComparator implements Comparator<Contact>
{
public int compare(Contact a, Contact b)
{
if (a.getFirstname().compareTo(b.getFirstname()) == 0)
return a.getFirstname().compareTo(b.getFirstname());
return a.getLastname().compareTo(b.getLastname());
}
}
Thanks.
The reason why remove(int) is not working is because is not executed.
In your case is that you wrongly compare reference type.
if (answer2 == "y"){
contacts.remove(foundPosition); // **HERE is where I need help.**
When using objects to check that are equal you should call method equals
if ("y".equalsIgnoreCase(answer2)){ // **HERE is where You needed help.**
contacts.remove(foundPosition);
You can read more about it here:
How do I compare strings in Java?