Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Below is the code. I cannot figure out why in class Database my else if the state runs simultaneously with my if statement IF I have entered the second bird into the ArrayList. please, any help would be appreciated!
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Database d1 = new Database();
while (true) {
System.out.println("What do you want to do?");
String answer = input.nextLine();
if(answer.equalsIgnoreCase("Add")){
System.out.println("Name: ");
String name = input.nextLine();
System.out.println("Latin name: ");
String lName = input.nextLine();
d1.addBird(name, lName);
} else if (answer.equalsIgnoreCase("O")) {
System.out.println("What was observed?");
String observed = input.nextLine();
d1.Observation(observed);
} else if (answer.equalsIgnoreCase("stats")) {
d1.showBirds(); //Displays all with observations.
} else if (answer.equalsIgnoreCase("show")) {
System.out.println("What?");
String search = input.nextLine();
d1.searchBird(search);
} else if (answer.equalsIgnoreCase("quit")){
break;
}
}
}
}
public class Bird {
private final String name;
private final String latinName;
private int count;
public Bird (String name, String latinName) {
this.name = name;
this.latinName = latinName;
this.count = count;
}
public String getName () {
return this.name;
}
public String getLatin() {
return this.latinName;
}
public String add () {
return this.name + " " + "(" +this.latinName + ")"+ " " + this.count + " observation(s)";
}
public void increaseCount () {
this.count++;
}
}
import java.util.ArrayList;
public class Database {
private final ArrayList<Bird> birdList;
public Database() {
this.birdList = new ArrayList<Bird>();
}
public void addBird (String name, String lname) {
this.birdList.add(new Bird(name, lname));
}
public void Observation (String observed) {
for (Bird x : getBirds()) { // this has to be a method
if (x.getName() != null && x.getLatin() != null && x.getName().contains(observed) || x.getLatin().contains(observed)) {
System.out.println("Done");
System.out.println("");
x.increaseCount();
} else if (x.getName() != observed || x.getLatin() != observed) {
System.out.println("Not a bird");
}
}
}
public void showBirds () {
for (Bird x : this.birdList) {
System.out.println(x.add());
}
}
public ArrayList<Bird> getBirds() {
return this.birdList;
}
public void searchBird(String search) {
for (Bird x : getBirds()) {
if (x.getName().contains(search)) {
System.out.println(x.add());
}
}
}
}
I think the problem lies in this method:
public void Observation (String observed) {
for (Bird x : getBirds()) { // this has to be a method
if (x.getName() != null && x.getLatin() != null && x.getName().contains(observed) || x.getLatin().contains(observed)) {
System.out.println("Done");
System.out.println("");
x.increaseCount();
}
/* No need to print "Not a bird" for every mismatch. Use a flag instead */
else if (x.getName() != observed || x.getLatin() != observed) {
System.out.println("Not a bird");
}
}
}
Do something like this:
public void Observation (String observed) {
boolean found = false;
for (Bird x : getBirds()) { // this has to be a method
if (x.getName() != null && x.getLatin() != null && x.getName().contains(observed) || x.getLatin().contains(observed)) {
System.out.println("Done");
System.out.println("");
x.increaseCount();
found = true;
}
}
if (!found) {
System.out.println("Not a bird");
}
}
Related
I am not too familiar with polymorphism, and was wondering if I have it used in my code?
If this doesn't contain a polymorphic reference, could you lead me in a direction of where I would need to go? The files that the program is using are not included, as I am mainly curious about whether or not any polymorphic references are used.
java file 1 - this file runs the program
import java.util.Scanner;
public class ADTDemo {
ADTDictionary dictionary;
public static void menu() {
System.out.println("Welcome the Faculty Directory Program");
System.out.println(" Use commands:");
System.out.println(" list all");
System.out.println(" list DEPT_NAME");
System.out.println(" add DEPT_NAME, FIRST LAST");
System.out.println(" remove DEPT_NAME, FIRST LAST");
System.out.println(" exit");
}
public static void main(String[] args) {
menu();
String command;
ADTDemo dictObj = new ADTDemo();
dictObj.dictionary = new ADTDictionary();
dictObj.dictionary.read();
Scanner scanner = new Scanner(System.in);
do {
System.out.println("");
System.out.print(">>");
command = scanner.nextLine().trim();
if (!command.equals("exit")) {
dictObj.action(command);
} else {
dictObj.dictionary.saveEntries();
System.out.println("Goodbye! Have a nice day!");
}
} while (!command.equalsIgnoreCase("exit"));
}
public void action(String command) {
if (command.equalsIgnoreCase("LIST ALL")) {
dictionary.listAll();
return;
}
else if (command.toUpperCase().contains("LIST")) {
if (command.length() == 4){
System.out.println("Command needed.");
return;
}
command = command.substring(5, command.length());
dictionary.listDeptName(command);
return;
}
else if (command.toUpperCase().contains("ADD")) {
command = command.substring(4, command.length());
dictionary.add(command);
return;
}
else if (command.toUpperCase().contains("REMOVE")) {
command = command.substring(6, command.length());
dictionary.remove(command);
}
}
}
java file 2
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ADTDictionary {
Map<String, List<String>> adtDictionary;
public void read() {
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
Scanner departmentScanner = new Scanner(departmentFile);
Scanner facultyScanner = new Scanner(facultyFile);
adtDictionary = new HashMap<String, List<String>>();
while (departmentScanner.hasNextLine()) {
String department = departmentScanner.nextLine().trim();
adtDictionary.put(department, new ArrayList<String>());
}
while (facultyScanner.hasNextLine()) {
String faculty = facultyScanner.nextLine();
String[] values = faculty.split(",");
adtDictionary.get(values[1].trim()).add(values[0]);
}
} catch (FileNotFoundException ex) {
System.out.println("ERROR: File not found.");
}
}
public void listAll() {
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
System.out.println(value + ", " + key);
}
}
}
public void listDeptName(String department) {
if (null != adtDictionary.get(department)) {
for (String name : adtDictionary.get(department)) {
System.out.println(name);
}
}
else{
System.out.println("Unknown entry made.");
}
}
public void add(String value) {
if(!value.contains(",")){
System.out.println("Incorrect entry.");
return;
}
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
String[] facName = faculty.split(" ");
if (!(facName.length == 2)){
System.out.println("Please only enter First and Last name of faculty member.");
return;
}
if (!(null != adtDictionary.get(dept))) {
if(adtDictionary.containsKey(dept.toUpperCase())){
System.out.println("Incorrect departtment entry.");
return;
}
else if (dept == dept.toUpperCase()){
adtDictionary.put(dept, new ArrayList<String>());
}
else{
System.out.println("Incorrect department entry.");
return;
}
}
for (String name : adtDictionary.get(dept)) {
if (name.equalsIgnoreCase(faculty)) {
System.out.println("Cannot add " + name + " to " + dept + " because they already exist there.");
return;
}
}
adtDictionary.get(dept).add(faculty);
System.out.println("OK, added " + faculty);
}
public void remove(String value) {
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
adtDictionary.get(dept).remove(faculty);
System.out.println("OK, removed " + faculty + " from " + dept);
}
public void saveEntries(){
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
PrintWriter facWriter = new PrintWriter(facultyFile);
PrintWriter deptWriter = new PrintWriter(departmentFile);
for (Object s : adtDictionary.keySet()) {
deptWriter.println(s);
}
deptWriter.close();
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
facWriter.println(value + ", " + key);
}
}
facWriter.close();
}
catch (IOException ex){
System.out.println("ERROR saving file.");
}
}
}
Attempting to get this output at the 2nd last part:
/*****test finalistsToFile2 with sorted arraylist*****/
/**************check file testSorted.txt**************/
/****************************************************/
However, my actual output is:
/****************************************************/
/*****test finalistsToFile2 with sorted arraylist*****/
/**************check file testSorted.txt**************/
**ID: 85011, Final Mark: 69.2, Classification: UPPER_SECOND
Candidate is BORDERLINE
ID: 62138, Final Mark: 59.9, Classification: LOWER_SECOND
Candidate is BORDERLINE**
/****************************************************/
I've attempted debugging but still cannot find the root cause of the extra 4 lines of printing under 'check file testSorted.txt' (in bold). Any idea what I can do? I have a total of 3 classes used as shown below:
ProcessDegreeMark class
import java.util.*;
import java.io.*;
public class ProcessDegreeMark{
private ProcessDegreeMark() {}
public static ArrayList<Finalist> finalistsInList(String s) throws Exception{
ArrayList<Finalist> finalists = new ArrayList<Finalist>();
String id;
double mark;
Scanner in = null;
try
{
in = new Scanner(new FileReader(s));
try
{
while(in.hasNextLine())
{
id =in.nextLine();
mark = Double.parseDouble(in.nextLine());
finalists.add(new Finalist(id,mark));
}
}
finally
{
in.close();
}
}
catch(IOException e)
{
System.out.println(s+" not found");
}
return finalists;
}
public static void displayFinalists(ArrayList<Finalist> finalists){
for (int i = 0; i < finalists.size(); i++)
{
System.out.println(finalists.get(i));
}
}
public static void findFinalistID(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getId().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with ID number "+s);
}
}
public static void findFinalistClass(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static ArrayList<Finalist> sortDegreeMark(ArrayList<Finalist> a){
ArrayList<Finalist> sortedFinalists = new ArrayList<Finalist>();
sortedFinalists.addAll(a);
Collections.sort(sortedFinalists, new FinalistComparator());
return sortedFinalists;
}
public static void finalistsToFile2(ArrayList<Finalist> finalists, String s) {
try
{
PrintStream out = new PrintStream(new FileOutputStream(s));
try
{
for(int i = 0; i < finalists.size(); i++)
{
out.println(finalists.get(i));
}
}
finally
{
out.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void findAndSaveFinalistClass(ArrayList<Finalist> a, String s){
ArrayList<Finalist> searchFinalists = new ArrayList<Finalist>();
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
searchFinalists.add(a.get(i));
finalistsToFile2(searchFinalists,"testSorted.txt");
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static void main(String[] args) throws Exception{
System.out.println("/****************************************************/");
System.out.println("/*******finalistsInList with invalid file name*******/");
System.out.println();
ArrayList<Finalist> testList = finalistsInList("file***.txt");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/********finalistsInList with valid file name********/");
System.out.println("/********display to check arraylist populated********/");
System.out.println();
ArrayList<Finalist> finalists = finalistsInList("finalMark.txt");
displayFinalists(finalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*testing findFinalistID with valid and invalid data*/");
System.out.println();
findFinalistID(finalists, "75021");
findFinalistID(finalists, "21050");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findFinalistClass with valid and invalid data*/");
System.out.println();
findFinalistClass(finalists, "FIRST");
findFinalistClass(finalists, "THIRD");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****run sortedFinalists then test with display*****/");
System.out.println();
ArrayList<Finalist> sortedFinalists = sortDegreeMark(finalists);
displayFinalists(sortedFinalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****test finalistsToFile2 with sorted arraylist*****/");
System.out.println("/**************check file testSorted.txt**************/");
System.out.println();
finalistsToFile2(sortedFinalists, "testSorted.txt"); //save the sorted arraylist to a new file, check by opening file
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findAndSaveFinalistClass with valid and invalid data*/");
System.out.println();
findAndSaveFinalistClass(finalists, "FIRST"); //test method finds
findAndSaveFinalistClass(finalists, "THRID"); //check appropriate error message when nothing found, open new text file
System.out.println();
System.out.println("/*********************THE END************************/");
}
}
Finalist class
public class Finalist{
private String id;
private double degreeMark;
private String degreeClass;
private boolean borderline;
public Finalist(String id, double degreeMark) {
this.id = id;
this.degreeMark = degreeMark;
borderline = calcBorderline();
degreeClass = assignDegreeClass();
}
private String assignDegreeClass(){//change method name
if (degreeMark<40) return "FAIL";
if (degreeMark<50) return "THIRD";
if (degreeMark<60) return "LOWER_SECOND";
if (degreeMark<70) return "UPPER_SECOND";
return "FIRST";
}
private boolean calcBorderline(){
double x;
if (degreeMark<40){
x = 40.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<50){
x = 50.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<60){
x = 60.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<70){
x = 70.0-degreeMark;
if (x < 1.0) return true;
}
return false;
}
public String getId(){
return id;
}
public double getDegreeMark(){
return degreeMark;
}
public String getdegreeClass(){
return degreeClass;
}
public boolean getborderline(){
return borderline;
}
public String toString() {
String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
if(calcBorderline()==true)
{
System.out.print(s);
System.out.println("Candidate is BORDERLINE");
}
else if(calcBorderline()==false)
{
return s;
}
return "";
}
}
FinalistComparator class
import java.util.Comparator;
//sort by degree mark, descending
class FinalistComparator implements Comparator<Finalist> {
#Override
public int compare(Finalist f1, Finalist f2) {
int degreeComparisonResult = Double.compare(f2.getDegreeMark(),f1.getDegreeMark());
return degreeComparisonResult;
}
}
The unexpected output is performed in Finalist.toString() because of out.println(finalists.get(i));. Since PrintStream.println(Object x) calls toString() of the provided Object.
Update: since you stated that you need the second line: Candidate is BORDERLINE just add it to the return value and don't directly print it on System.out else you will get unexpected outputs.
#Override
public String toString() {
String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
if(calcBorderline()) {
s += "Candidate is BORDERLINE" + System.lineSeparator();
}
return s;
}
Original answer:
So avoid the use of System.out.println() in toString(), i would recommand to keep it as simple as possible and put logic in another method.
For example:
public class Finalist{
/* all the other code */
#Override
public String toString() {
return "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass;
}
}
public class ProcessDegreeMark {
/** Writes all non BORDERLINE candidates in the file and outputs the skipped finalists to System.out */
public static void saveToFileWithoutBorderline(List<Finalist> list, File file) {
try (PrintStream out = new PrintStream(new FileOutputStream(file))){
for(Finalist finalist : list) {
if(finalist.calcBorderline()) {
System.out.println("Skip BORDERLINE candidate: "+finalist.toString());
} else {
out.println(finalist.toString());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I only provided a sample code to skip the borderline candidates in saveToFile, since I didn't know where you have to skip or suppress them.
I have created three methods readLong, readInt and readDouble that basically does the same thing. Only difference is the method called by a scanner. How can I reduce duplicate code by turning them all to one method?
public long readLong(String description)
{
System.out.println(description);
long nrToReturn = 0;
boolean acceptedValue = false;
do {
System.out.println();
System.out.print("Choose one: ");
try
{
nrToReturn = consoleScanner.nextLong(); //Only line thats different except return value
acceptedValue = true;
}catch(Exception e)
{
acceptedValue = false;
consoleScanner.nextLine();
}
}while (!acceptedValue);
consoleScanner.nextLine();
return nrToReturn;
}
Here we go with one idea:
import java.util.Scanner;
public class ScannerTest {
private Scanner consoleScanner;
public ScannerTest() {
consoleScanner = new Scanner(System.in);
}
#SuppressWarnings("unchecked")
private <T extends Number> T readType(String description, Class<T> desiredType) {
System.out.println(description);
Number result = null;
while (result == null) {
System.out.println();
System.out.print("Choose one: ");
try {
if (Integer.class.equals(desiredType)) {
result = new Integer(consoleScanner.nextInt());
} else if (Long.class.equals(desiredType)) {
result = new Long(consoleScanner.nextLong());
}
} catch(Exception e) {
consoleScanner.nextLine();
}
}
consoleScanner.nextLine();
return (T) result;
}
public long readLong(String description) {
return this.readType(description, Long.class);
}
public int readInt(String description) {
return this.readType(description, Integer.class);
}
public static void main(String[] args) {
ScannerTest t = new ScannerTest();
t.readLong("Reading a long value...");
t.readInt("Reading an integer value...");
}
}
Update, following #Michu93 idea of a single transparent method:
import java.util.Scanner;
public class ScannerTest {
private Scanner consoleScanner;
public ScannerTest() {
consoleScanner = new Scanner(System.in);
}
#SuppressWarnings("unchecked")
public <T extends Number> T readNumber(String description) {
System.out.println(description);
Number result = null;
while (result == null) {
System.out.print("\nChoose one: ");
String textRead = consoleScanner.next();
try {
result = new Integer(textRead);
} catch(Exception e1) {
try {
result = new Long(textRead);
} catch (Exception e2) {
try {
result = new Double(textRead);
} catch (Exception e3) {
}
}
}
consoleScanner.nextLine();
}
return (T) result;
}
public static void main(String[] args) {
ScannerTest t = new ScannerTest();
for (int i = 0; i < 3; i++) {
Number input = t.readNumber(i + ": Reading int, long or double...");
System.out.println("Input class: " + input.getClass().getCanonicalName());
System.out.println("Input value: " + input);
}
}
}
I'm completely brand new to programming (started yesterday...) and Java so excuse any stupid mistakes and really awful code (I have no clue how to order/format). I've been given a task to make an inventory of videos and I want to be able to search through the inventory to check if a particular video is there.
I know I can use contains to do this but I can't get it to work with my custom objects ArrayList (videos) and I want it to search through all the data (each InventoryRow below). I've overridden equals and HashCode but it still won't work - whenever I try to run the code it will always tell me it can't find the video even if the video is there. (FYI I use contains towards the end of my code under the rent and check functions)
I'd really appreciate any help as I've been googling all day to no avail. Also if this can't be done or another method would be better please let me know! Thanks.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
class InventoryRow {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((availability == null) ? 0 : availability.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((returndate == null) ? 0 : returndate.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InventoryRow other = (InventoryRow) obj;
if (availability == null) {
if (other.availability != null)
return false;
} else if (!availability.equals(other.availability))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (returndate == null) {
if (other.returndate != null)
return false;
} else if (!returndate.equals(other.returndate))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
private String name;
private String type;
private Character availability;
private String returndate;
public InventoryRow(String name, String type, Character availability,
String returndate) {
this.name = name;
this.type = type;
this.availability = availability;
this.returndate = returndate;
}
public String getReturndate() {
return returndate;
}
public void setReturndate(String returndate) {
this.returndate = returndate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Character getAvailability() {
return availability;
}
public void setAvailability(Character availability) {
this.availability = availability;
}
public String toString() {
return name + " " + type + " " + availability + " " + returndate;
}
}
public class InventorySort {
public static void main(String[] args) {
List<InventoryRow> videos = new ArrayList<InventoryRow>();
videos.add(new InventoryRow("Casablanca", "Old", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
"1 January 2015"));
videos.add(new InventoryRow("2012", "Regular", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Ant-Man", "New", 'Y', "1 January 2015"));
// Another ArrayList because I can't seem to search through the first
// one?
/*ArrayList<String> names = new ArrayList<String>();
names.add("Casablanca");
names.add("Jurassic Park");
names.add("2012");
names.add("Ant-Man");*/
Scanner input = new Scanner(System.in);
// Output the prompt
System.out.println("What do you want to do?");
// Wait for the user to enter a line of text
String line = input.nextLine();
// List, rent and check functions
// List function
if (line.equals("l")) {
// Sort function
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
// Rent function
} else if (line.equals("r")) {
System.out.println("Which video would you like to rent?");
String line2 = input.nextLine();
// Search through ArrayList
if (videos.contains(line2)) {
System.out.println("Video available to rent!");
} else {
System.out.println("Video unavailable to rent.");
}
// Check function
} else if (line.equals("c")) {
System.out
.println("Which video would you like to check is in the inventory?");
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(line3)) {
System.out.println("Video found!");
} else {
System.out
.println("Video not found. Please see the inventory below.");
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
// If anything else is entered
} else {
System.out
.println("The only options are to list (l), rent (r) or check (c).");
}
}
}
You can use contains. But, for the first day of programming, it might be more understandable to simply iterate over your inventory, comparing the input string with the video name:
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line3.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");
Alternative to #kilo answer, you could implement equals and hashcode method only on the name of video class and check it in the following way.
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(new Video(line3, null, null, null))) {
System.out.println("Video found!");
}
This will return contains = true only if the name matches.
I have an assignment to carry out using BlueJ where I am given a class called HW4CustomerList and I must create a Text-Based UI for it. The class I have to create is called CustomerTUI and contains a method called addCustomer which adds a new Customer object of mine to an ArrayList. This method in particular is what I am stuck with. The class specification says that I cannot take any parameters (i.e. a no-args method). In previous work we have used the BlueJ 'method box' to interact with objects and add them to ArrayLists, however I do not know if this can be used in this particular instance. Please find below my code so far for CustomerTUI and the code for the Customer class and HW4CustomerList class. Many thanks in advance.
CustomerTUI class:
import java.util.Scanner;
public class CustomerTUI
{
private HW4CustomerList customerList;
private Scanner myScanner;
public CustomerTUI()
{
customerList = new HW4CustomerList();
myScanner = new Scanner(System.in);
}
public void menu()
{
int command;
boolean running = true;
while(running)
{
displayMenu();
command = getCommand();
execute(command);
}
}
private void addCustomer()
{
customerList.addCustomer();
}
private void displayMenu()
{
System.out.println(" CustomerList program ");
System.out.println("=========================================");
System.out.println("|Add a customer to the list..........[1]|");
System.out.println("|Get number of customers.............[2]|");
System.out.println("|Remove a customer from the list.....[3]|");
System.out.println("|Show all customer details...........[4]|");
System.out.println("|Show a specific customers details...[5]|");
System.out.println("|Quit................................[6]|");
System.out.println("=========================================");
}
private void execute(int command)
{
if(command == 1)
{
addCustomer();
}
else if(command == 2)
{
getNumberOfCustomers();
}
else if(command == 3)
{
removeCustomer();
}
else if(command == 4)
{
showAllCustomers();
}
else if(command == 5)
{
showCustomer();
}
else if(command == 6)
{
quitCommand();
}
else
{
unknownCommand(command);
}
}
private int getCommand()
{
System.out.println("Enter the command of the function you wish to use: ");
int command = myScanner.nextInt();
return command;
}
private void getNumberOfCustomers()
{
if(customerList.getNumberOfCustomers() == 1)
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customer.");
}
else
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customers.");
}
}
private void quitCommand()
{
System.out.println("The program is now closing down...");
System.exit(0);
}
private void removeCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to remove: ");
accNo = myScanner.next();
if (customerList.removeCustomer(accNo) == true)
{
System.out.println("Customer with account number " + accNo + " was successfully removed.");
}
else
{
System.out.println("Customer with account number " + accNo + " was NOT successfully removed.");
System.out.println("Please try again.");
}
}
private void showAllCustomers()
{
customerList.getAllCustomers();
}
private void showCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to view: ");
accNo = myScanner.next();
if(customerList.getCustomer(accNo) == false)
{
System.out.println("Could not find customer with account number " + accNo + ".");
}
else
{
return;
}
}
private void unknownCommand(int command)
{
System.out.println("Command number " + command + " is not valid. Please try again.");
}
}
HW4CustomerList class:
import java.util.*;
public class HW4CustomerList
{
private ArrayList<Customer> customers;
public HW4CustomerList()
{
customers = new ArrayList<Customer>();
}
public void addCustomer(Customer customer)
{
customers.add(customer);
}
public int getNumberOfCustomers()
{
return customers.size();
}
public boolean getCustomer(String accountNumber)
{
for(Customer customer : customers)
{
if(accountNumber.equals(customer.getAccountNumber()))
{
customer.printCustomerDetails();
return true;
}
}
return false;
}
public void getAllCustomers()
{
for(Customer customer : customers)
{
customer.printCustomerDetails();
System.out.println("\n");
}
}
public boolean removeCustomer(String accountNumber)
{
int index = 0;
for (Customer customer: customers)
{
if (accountNumber.equals(customer.getAccountNumber()))
{
customers.remove(index);
return true;
}
index++;
}
return false;
}
}
I think all you need to do is create a new Customer object in your addCustomer() method. This would probably require getting additional details:
public void addCustomer()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter customer name: ");
String name = scanner.nextLine();
//any additional details
Customer customer = new Customer(name, otherParams);
customers.add(customer);
}
Hope that helps!