Search arraylist of objects does not work - java

I have been encountering a specific problem where only the first item in Arraylist is included when it comes to iterating each element in Arraylist (to search/to remove). That means that the second until n-1 iteams won't be found whenever I try to iterate.
Edited: currently improving my code.
You could try the following program. It is perfectly working only when adding the first record of the order: I can remove and search its values. However, when adding the second order: I can not remove and search its values, rather it is not found.
Source code
import java.util.*;
import java.io.*;
public class TestOrders {
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchElementException {
File afile = new File("order.txt");
FileOutputStream outFile = new FileOutputStream("order.txt");
ObjectOutputStream outStream = new ObjectOutputStream(outFile);
FileInputStream inFile = new FileInputStream("order.txt");
ObjectInputStream inStream = new ObjectInputStream(inFile);
//Create an arraylist of order
ArrayList<Order> theorder = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Order");
System.out.println("Please choose an option (1-5): ");
int choice = 0;
try {
while (choice != 5) {
//A list of options
System.out.println("\n1. Add a new order: ");
System.out.println("2. Search an order: ");
System.out.println("3. Compute sum of all orders:");
System.out.println("4. Remove an order: ");
System.out.println("5. Exit: ");
//prompt user
System.out.print("Pick a number: ");
if (scan.hasNextInt()) {
choice = scan.nextInt();
}
switch(choice) {
case 1:
addNewOrder(outStream, theorder);
break;
case 2:
searchOrder(outStream, inStream, theorder);
break;
case 3:
computeSum(afile, theorder);
break;
case 4:
removeOrder(outStream, inStream, theorder);
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Please enter from (1-5)");
}
}
} catch (IOException | InputMismatchException ex) {
System.out.println(ex);
} finally {
if (choice == 5) {
scan.close();
outStream.close();
inStream.close();
}
}
}
public static void addNewOrder(ObjectOutputStream outStream, ArrayList<Order> theorder) throws IOException {
Scanner input = new Scanner(System.in);
Order anorder = new Order();
System.out.print("Enter the order ID: ");
anorder.setOrderID(input.nextInt());
input.nextLine();
System.out.print("Enter the customer name: ");
anorder.setCustomerName(input.nextLine());
System.out.print("Enter the order (meal/drink): ");
anorder.setOrderType(input.nextLine());
System.out.print("Enter the order price: ");
anorder.setPrice(input.nextDouble());
if(theorder.size() <= 1000) {
theorder.add(anorder);
outStream.writeObject(anorder);
System.out.println("Order information saved.\n");
} else {
System.out.println("There is not enough space.");
}
}
public static void searchOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
Order o = new Order();
System.out.println("Please enter a customer ID: ");
int custID = input.nextInt();
for (Order or : theorder) {
if(or.getOrderID() == custID) {
System.out.println(or.toString());
break;
} else {
System.out.println("No matching record found");
break;
}
}
}
public static void computeSum(File aFile, ArrayList<Order> theorder) throws FileNotFoundException, IOException {
double sum = 0;
for (Order o : theorder) {
sum += o.getPrice();
}
sum = (double) Math.round(sum*100)/100;
System.out.println("The total sum of price for " + theorder.size() + " orders is " + sum);
}
public static void removeOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) {
Iterator<Order> iterator = theorder.iterator();
Scanner input = new Scanner(System.in);
System.out.println("Enter the order ID to remove: ");
int custID = input.nextInt();
while (iterator.hasNext()) {
Order anorder = iterator.next();
if(anorder.getOrderID() == custID) {
theorder.remove(anorder);
System.out.println(anorder.toString());
break;
} else {
System.out.println("Not found\n");
break;
}
}
for (Order o : theorder) {
System.out.println(o.toString());
}
}
}
Order class
import java.util.*;
import java.io.*;
public class Order implements Serializable {
private int orderID;
private String customerName;
private String orderType;
private double price;
public Order() {
}
public Order(int orderID, String customerName, String orderType, double price) {
this.orderID = orderID;
this.customerName = customerName;
this.orderType = orderType;
this.price = price;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public String getCustomerName() {
return this.customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getOrderType() {
return this.orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return this.orderID + " " + this.customerName + " " + this.orderType + " " + this.price + "\n";
}
}
This part is where I am struggling. I had tried using iterator but it got the same result, second item cannot be iterated/found.
for (Order o : theorder) {
if(o.getOrderID() == orderIDSearch) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
What should I do to fix this problem? is there any way it can be solved?

for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
There are several problems here:
First, removal of an element of a collection whilst iterating across the collection requires a different technique than you are using. Generally, modifying a collection in the midst of iteration will result in a ConcurrentModificationException.
Second, are multiple matches expected? If there is at most one match, the continue should be a break.
Third, one would expect the code to continue to following elements when a current element is not a match. That is, the break should be a continue, or better yet, should be removed entirely.
Fourth, its not clear that theorder.remove(orderIDSearch) will do anything, unless the collection type has a remove operation which takes a key value instead of an element value. For basic collection types (List, Set), the call won't do anything.
Here are two rewrites:
If the iterator supports remove:
Iterator<Order> orders = theorder.iterator();
boolean found = false;
while ( !found && orders.hasNext() ) {
if ( orders.next().getOrderID() == orderIDSearch ) {
found = true;
}
}
if ( found ) {
orders.remove();
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
If the iterator does not support remove, then:
boolean found = false;
for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
found = true;
break;
}
}
if ( found ) {
theorder.remove(orderIDSearch);
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
Note that this relies on remove accepting a key as the parameter value.

You are breaking the loop in for search in else condition.
Why would you do that.. Remove the else part

Related

Storing several different bits of data into a linked list

I am needing to store 3 different bits of data into a linked list. the first is a name, which i have working, then i need to store the employee number and their occupation. I can't find anything about linking a node to a set of data. any help would be greatly appreciated.
This is the code that runs, TeamMemberTest:
package teammember;
import java.util.*;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String args[]) {
/* Linked List Declaration */
LinkedList<String> linkedlist = new LinkedList<String>();
Scanner input = new Scanner(System.in);
boolean mainloop = true;
String name;
int employeeNo;
String position;
int choice;
while(true){
System.out.println("Menu");
System.out.print("1. add project \n");
System.out.print("2. display project \n");
System.out.print("3. remove project \n");
System.out.print("4. display all projects \n");
System.out.print("\nEnter your option: ");
choice = input.nextInt();
switch(choice){
case 1:
/*add(String Element) is used for adding
* the elements to the linked list*/
name = Input.getString("name: ");
employeeNo = Input.getInteger("Enter employee number: ");
position = Input.getString("Enter employee position: ");
linkedlist.add(name);
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
break;
case 2:
name = Input.getString("name: ");
if(linkedlist.contains(name)){
System.out.println("LinkedList does contain " + name);
}
break;
case 3:
name = Input.getString("name: ");
linkedlist.remove(name);
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
break;
case 4:
System.out.println("Linked List Content: " +linkedlist);
break;
default :
System.out.println("This is not a valid option try again.");
break;
}
}
}
}
this code below is TeamMember.java:
package teammember;
public class TeamMember {
//variables
private String name;
private int employeeNo;
private String position;
//the default constant
public TeamMember(){
name = " ";
employeeNo = 0;
position = " ";
}
//overload the constructor
public TeamMember(String name, int employeeNo, String position){
this.name = name;
this.employeeNo = employeeNo;
this.position = position;
}
//the methods
public void setName(String name){
this.name = name;
}
public void setemployeeNo(int employeeNo){
this.employeeNo = employeeNo;
}
public void setPosition(String position){
this.position = position;
}
public String getName(){
return name;
}
public int getemployeeNo(){
return employeeNo;
}
public String getPosition(){
return position;
}
}
and this is the input code:
package teammember;
import java.io.*;
public class Input{
private static BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
public static Character getCharacter(String prompt){
Character value;
System.out.print(prompt);
try{
value=Input.input.readLine().charAt(0);
}
catch(Exception error){
// error condition
value=null;
}
return value;
}
public static Double getDouble(String prompt){
Double value;
System.out.print(prompt);
try{
value=Double.parseDouble(Input.input.readLine());
}
catch(Exception error){
// error condition
throw new NumberFormatException();
}
return value;
}
public static Integer getInteger(String prompt){
Integer value;
System.out.print(prompt);
try{
value=Integer.parseInt(Input.input.readLine());
}
catch(Exception error){
// error condition
throw new NumberFormatException();
}
return value;
}
public static String getString(String prompt){
String string;
System.out.print(prompt);
try{
string=Input.input.readLine();
}
catch(Exception error){
// error condition
string=null;
}
return string;
}
}
Instead of creating a LinkedList of String, you need to create a LinkedList of TeamMember as follows:
LinkedList<TeamMember> linkedlist = new LinkedList<TeamMember>();
Then you need to change the cases accordingly e.g.
choice = input.nextInt();
boolean found;
switch (choice) {
case 1:
name = Input.getString("name: ");
employeeNo = Input.getInteger("Enter employee number: ");
position = Input.getString("Enter employee position: ");
linkedlist.add(new TeamMember(name, employeeNo, position));
break;
case 2:
found = false;
name = Input.getString("name: ");
for (TeamMember teamMember : linkedlist) {
if (teamMember.getName().equalsIgnoreCase(name)) {
System.out.println("Name: " + teamMember.getName() + "Employee No.: "
+ teamMember.getemployeeNo() + "Position: " + teamMember.getPosition());
found = true;
break;
}
}
if (!found) {
System.out.println("The team member was not found.");
}
break;
case 3:
found = false;
name = Input.getString("name: ");
for (TeamMember teamMember : linkedlist) {
if (teamMember.getName().equalsIgnoreCase(name)) {
linkedlist.remove(teamMember);
found = true;
break;
}
}
if (found) {
System.out.println("LinkedList after deletion of " + name + "'s record" + ": " + linkedlist);
} else {
System.out.println("The team member was not found.");
}
break;
case 4:
System.out.println("Linked List Content: " + linkedlist);
break;
default:
System.out.println("This is not a valid option try again.");
break;
}
Make sure to add a toString() method in the class, TeamMember so that you can simply do like System.out.println(an-object-of-TeamMember);. Your IDE can generate the toString() method on the click of a button. Given below is an autogenerated toString() method for your class by eclipse IDE:
#Override
public String toString() {
return "TeamMember [name=" + name + ", employeeNo=" + employeeNo + ", position=" + position + "]";
}
Check this to learn more about toString().

Java hasNext() and element() Implementation in While Loop

I'm having problems with my Iterator and Deque method and Here's my code:
import java.util.*;
import java.util.Iterator;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public ListIterator<E> iterator = list.listIterator();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public E show(){
return list.peek();
}
public void printQueueElements(){
}
public E isNotEnd(){
return list.getLast();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public Iterator<E> iterator()
{
return iterator;
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public boolean hasNext()
{
return false;
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
}
public class Jerald {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
while(true){
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
int numberOfElements = empList.size();
for (int i = 0; i < numberOfElements; i++) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n");
empList.enqueue(emp);
}
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
in case 1, I'm trying to make it retrieve all elements that are in my queue and print it out. Without removing them from there. So basically, instead of using while(hasItems) and poll() which I accomplished and it showed the output that i want, but it deletes everything in the list, so I came up with another approach and used the hasNext method so I used while(empLst.hasNext()) with element() method which only retrieves but does not delete. Unfortunately I have failed on this and have been getting either an empty result after many inputs, or an infinite loop after giving even a single input. How do I fix this? Need help. I think its on my implementation, but I think I have checked already. Anyway I need your opinion on this.
by the way in case 2, im removing the first elementof the linkedlist and showing the first element of the removed linkedlist.
To get rid of your infinite loop problem, remove that outer while(true) loop. Cause infinite loops is exactly what those kinds of loops do, and you don't need it to get the kind of flow you want.
I also introduced a third choice to your menu which clears things up a bit, but I guess that's up to you.
As far as your list problems, fix that "dequeue" method in GenQueue so that it actually does a dequeue (removes the first element in the list), then your case 2 becomes easy.
For printing a list without removing its elements, make use of iterators. I got rid of that ListIterator field in your queue class because you don't need it. In fact, most of the methods you have in that class have already been implemented for you anyways. Take a look at the
List API
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
// return a customer with null values if empty? (up to you)
if (list.isEmpty())
return new Customer("","");
else
return list.remove(0);
}
public E isNotEnd(){
return list.getLast();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty() {
return list.isEmpty();
}
public Iterator<E> iterator() {
return list.iterator();
}
public E removeFirst() {
return list.removeFirst();
}
public E getFirst() {
return list.getFirst();
}
public int size() {
return list.size();
}
public boolean hasNext() {
return false;
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
do {
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("3,View queue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try {
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
break;
case 2:
System.out.println("Dequeued customer: " + empList.dequeue().toString());
break;
case 3:
System.out.println("\nThe customers' names are: \n");
Iterator<Genqueue<Customer>> it = empList.iterator();
while (it.hasNext()) {
Customer emp = it.next();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e) {
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
} while(choice != 0);
}
}
In case 1, after the do-while loop you want to print all the elements in the Queue and keep all the elements.
I see 2 possibilities:
1) Implement in GenQueue a method that iterates the inner list and prints each element without changing anything: public void printQueueElements().
This is the recommended solution.
2) Instead of:
while (empList.hasNext()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
Use:
int numberOfElements = empList.size();
for (int i = 0; i < numberOfElements; i++) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n");
empList.enqueue(emp);
}
This way the queue regains its elements.
The code for case 3 should be:
case 3:
System.out.println("\nThe customers' names are: \n");
Iterator<Customer> it = empList.iterator();
Note the type of the variable "it". Also, the convention is to call an iterator variable "itr" or "iterator".

Java Queue Program Results to Empty When Dequeueing

This is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
while(true){
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
while (empList.hasItems()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
I want to make a program that accepts queue and then can also dequeue. in case 1 i made the queue successfully, but at case 2, i encountered a certain trouble that I cant figure out that I have to stack overflow it, Im stuck here and I might just be missing out the trivial things on this code. So I need your help. Why does in case 2 my dequeue gets passed an empty list? How do i fix this? Thank you very much!
when you populate your hlist you dequeue all elements from empList and hence your empList will be empty at last.
while (q.hasItems()) list.addLast(q.dequeue());
You can rewrite your addItems method, to just iterate over the elements in the given queue and add them to its own LinkedList.

driver class what to do (array)

I am trying to create a driver class using array list of objects and it requires me to :
Read the book title from the user
Read the book ISBN from the user
Read the book in stock quantity from the user
program should continue to read the book information from the user until all the entries from the user for all the fields are blank or zero.
program will store valid book objects into an ArrayList (only valid objects)
Your program will then print the list all the "valid" Books entered by the user in the reverse order in which the books were entered.
As the user is entering information, the program should give feedback such as reporting that an item has been added to the ArrayList, or reporting any errors found.
Books with invalid entries were not added to the ArrayList, therefore they will not be printed when the ArrayList is printed
Here is my current code so far for my driver: (I'm a bit newb at this so )
edited: with the answer given
Here is what I got now
import java.io.*;
import java.util.*;
public class Bookstore2{
public static void main(String arg[ ]) throws Exception{
Scanner sc = new Scanner(System.in);
int isbn=0;
int quantity = 0;
String title = "";
Book oneBook;
List<Book> bookList = new ArrayList<Book>(); //here
while(true){
System.out.print("Enter title: ");
title = sc.nextLine( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
sc = new Scanner(System.in);
sc = new Scanner(System.in);
System.out.println();
// WRITE YOUR VALIDATION CODE HERE
// Change condition according to your requirements.
if(isbn !=0 && quantity != 0 && title != null && title != "")
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
} //main method
} //class
error now averted but it's not utilizing both my exception and book class it seems like
Here is my class and my exception that will be running with the new driver class
-----Class
public class Book{
//instance variables
private String title = "";
private int isbn;
private int quantity;
public Book (String title, int isbn, int quantity)throws BookException{
//constructors
setTitle(title);
setIsbn(isbn);
setQuantity(quantity);
}
public String toString( ){ //toString Method
String s = "";
s = s + "Title: " + this.title + "\nISBN: " + this.isbn + "\nQuantity: " + this.quantity + "\n";
return s;
}
public String getTitle( ){
return this.title;
}
public int getisbn( ){
return this.isbn;
}
public int getquantity( ){
return this.quantity;
}
//mutator methods
public void setTitle(String newtitle )throws BookException{
if(newtitle.length()<1){
BookException be = new BookException( );
be.setMessage("Title cannot be blank");
throw be;
}
else{
this.title=newtitle;
}
}
public void setIsbn(int newisbn)throws BookException{
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
}
else{
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
}
public void setQuantity(int newquantity)throws BookException{
if(newquantity>=0){
this.quantity = newquantity;
}
else{
BookException be = new BookException( );
be.setMessage("Quantity can't be a negative number.");
throw be;
}
}
}
------Exception Class
public class BookException extends Exception {
//instance variable
private String message = "";
public void setMessage(String newMessage) {
this.message = newMessage;
}
public String getMessage() {
return this.message;
}
}
First of all use: while(true) loop to iterate until user entered 0 for all the field.
while(true)
{
// Scanner Code i.e. read input from the user.
if(//check all the inputs)
{
//create a new book and insert it into array list
}
else
{
// If input is 0, break from the loop
}
}
Secondly, Never perform validation in your bean class. Create a separate class or method to validate the inputs. After, input validation only then create a new object.
Hope this will help you.
The correct code :
sc = new Scanner(System.in);
while(true){
System.out.print("Enter title: ");
title = sc.nextLine( );
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
System.out.println();
// WRITE YOUR VALIDATION CODE HERE
// Change condition according to your requirements.
if(isbn !=0 && quantity != 0 && title != null && title != "")
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
You posted :
while(title != null || title.equals("0") || isbn != null || isbn != 0 || quantity
isbn is of int type i.e. primitive type how can we compare it with a null.
quantity is also of int type.
Default value of an int i.e. primitive type is 0. And, primitive type can never be compared with null.
Since there is so much confusion on the code, here is a complete solution to the task:
Bookstore.java:
public class Bookstore {
static final Scanner in = new Scanner(System.in);
static List<Book> books = new ArrayList<>();
public static void main(String arg[]) throws Exception {
while (true) {
// read book information
Book book = new Book();
System.out.print("Enter title: ");
book.title = in.nextLine();
System.out.println();
System.out.print("Enter ISBN: ");
book.isbn = readInt();
System.out.println();
System.out.print("Enter quantity: ");
book.quantity = readInt();
System.out.println();
// exit condition: "blank book" entered
if (book.title.isEmpty() && book.isbn == 0 && book.quantity == 0) {
System.out.println("Goodbye!");
break;
}
//validate and add book
try {
validateBook(book);
books.add(book);
System.out.println("Book successfully added to the list.");
} catch (IllegalStateException ex) {
System.err.println("Book is not valid: " + ex.getMessage());
continue;
}
// print book list
for (int i = books.size() - 1; i >= 0; i--) {
System.out.println(books.get(i));
System.out.println();
}
}
}
static int readInt() {
while (true) {
String input = in.nextLine();
if(input.isEmpty()) {
return 0;
}
try {
return Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.err.println("Expected a valid integer: " + input);
}
}
}
static void validateBook(Book book) {
if (book.title == null || book.title.isEmpty()) {
throw new IllegalStateException("Book title must not be blank.");
}
if (book.isbn < 1000 || book.isbn > 10000) {
throw new IllegalStateException("Book ISBN must be between 1000 and 10000.");
}
if (book.quantity < 0) {
throw new IllegalStateException("Book quantity must be positive.");
}
}
}
Book.java:
public class Book {
public String title;
public int isbn;
public int quantity;
#Override
public String toString() {
return String.join("\n",
"Title: " + title,
"ISBN: " + isbn,
"Quantity: " + quantity
);
}
}

How to connect multiple ArrayLists in different classes. (Bank program in java)

I'm involved in a group assignment where we are supposed to create a bank program. This is our first time programming in java. We are stuck and we are having trouble figuring out how to connect our customer and account classes. They both consist of ArrayLists and we want the customer arraylists to contain the accounts. So that if we delete a customer, the accounts that belong to that customer will also be deleted. Can anyone give us a push in the right direction?
This is our main class which contains the bank menu:
package bank6;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Bankmenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Customer client = new Customer();
Account bank = new Account();
Account accs = new Account();
Customer cust1, cust2, cust3;
cust1 = new Customer("8905060000", "Henrik");
cust2 = new Customer("8910210000", "Emelie");
cust3 = new Customer("8611040000", "Fredrik");
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
client.addCustomerAr(cust1);
client.addCustomerAr(cust2);
client.addCustomerAr(cust3);
int ChoiceOne = 0;
int CustChoice;
int currentCustomer;
int currentAccount;
int amountC;
int amountD;
int editCust;
String personNummer = null;
String Pnr = "0";
int AdminChoice;
/*prompts the user to set ChoiceOne equal to 1 or 2. Hasnextint checks
if the input is an int. else asks for new input. */
while (ChoiceOne != 1 && ChoiceOne != 2) {
System.out.println("Press 1 to login as customer or 2 to login as admin ");
if (input.hasNextInt()) {
ChoiceOne = input.nextInt();
System.out.println();
} else {
System.out.println("You must enter number 1 or number 2");
input.next();
}//ends else
}//ends while
/*
If the user chooses 1 in the previous question, the user will be sent to
the interface for the customer. User is then asked to enter his social
security number and this number will be checked using the Luhn algoritm. Since
the scanner input is already used we added a new Scanner calleds nexLine
to deal with custPnr as a string.
(http://stackoverflow.com/questions/5032356/using-scanner-nextline)
*/
if (ChoiceOne == 1) {
//boolean quit=false;
while ("0".equals(Pnr)) {
// System.out.println("Welcome customer. Please login by using your birthdate (yymmddnnnn) ");
// Scanner nextLine = new Scanner(System.in);
// Pnr = nextLine.nextLine();
//Luhn.checkLogin(Pnr);
//Här måste en kontroll med Luhn algoritmen göras.
// getUserBirthdate();
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
/* }
Sets "quit" to false and executes quit=true if customer chooses case 0
*/
}
boolean quit = false;
do {
// boolean quit = false;
//System.out.println();
System.out.println("Logged on as " + personNummer);
System.out.println("1. deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
CustChoice = input.nextInt();
switch (CustChoice) {
case 1: //Deposit money
System.out.println(bank.getAccountNumbersFor(personNummer));
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to deposit:");
amountC = input.nextInt();
System.out.println(bank.creditAccount(currentAccount, amountC));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 2://Withdraw money
// System.out.println(bank.getAccNosFor(custPnr));
bank.getAccountNo();
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to withdraw:");
amountD = input.nextInt();
System.out.println(bank.debitAccount(currentAccount, amountD));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 3://Check ballance and accounts
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends if
else if (ChoiceOne == 2) {
while ("0".equals(Pnr)) {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
}
//AdminpNr = input.nextInt();
//Här måste en kontroll av AdminpNr göras med hjälp av Luhn.
boolean quit = false;
do {
System.out.println("1. Add customer");
System.out.println("2. Add account");
System.out.println("3. List customer");
System.out.println("4. List accounts");
System.out.println("5. Remove customer");
System.out.println("6. Remove account");
System.out.print("Your choice, 0 to quit: ");
AdminChoice = input.nextInt();
switch (AdminChoice) {
case 1://add customer
int i = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<String, Customer> testCustomers = new HashMap<String, Customer>();
String name = scan.nextLine();
//System.out.println("Att arbeta på bank ska vara jobbigt, skriv in det igen:");
//String pnummer = scan.nextLine();
String pnummer = name;
System.out.println("Skriv in namn:");
String kundnamn = scan.nextLine();
Customer obj = new Customer(pnummer, kundnamn);
testCustomers.put(name, obj);
client.addCustomerAr(obj);
i++;
} while (i < 2);
break;
case 2://add account
int i2 = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<Long, Account> testAccs = new HashMap<Long, Account>();
Long name = scan.nextLong();
//System.out.println("Skriv in personnummer igen:");
Long own = name;
long bal = 0;
Account obt = new Account(own, bal);
testAccs.put(name, obt);
accs.addAccAr(obt);
i2++;
} while (i2 < 2);
break;
case 3:// List customer and accounts
for (String info : client.getAllClients()) {
System.out.println(info);
}
break;
case 4:
for (Long infoAcc : accs.getAllAccounts()) {
System.out.println(infoAcc);
}
break;
case 5:
// ta bort kund
break;
case 6:
// ta bort konto
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends else if
}//ends main
/* private static void getUserBirthdate() {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner (System.in);
String personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
}
*/
}//ends class
This is our Account class;
package bank6;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Account {
private ArrayList accounts;
private Object lastAcc;
public String customerSocial;
private Integer balance;
private Integer accountNumber;
private Customer owner;
private Account Customer6; // Association customer/account.
private ArrayList<Account> myAccounts = new ArrayList<Account>();
public Integer deposit;
public Integer withdraw;
static Integer accountNo = 1010;
private Long persnr;
private long balans = 0;
/*Constructor.. A account cannot exist unless it is owned by a customer*/
public Account(Customer owner, Integer balance) {
this.owner = owner;
this.balance = balance;
accountNumber = accountNo++;
}
public Account() {
accounts = new ArrayList();
}
public Account(Long persnr, long balans) {
this.persnr = persnr;
this.balans = balans;
accountNumber = accountNo++;
}
public Integer getAccountNo() {
return accountNumber;
}
public String getOwner() {
return owner.getName();
}
public Customer getOwn() {
return owner;
}
public Integer getBalance() {
return balance;
}
//credits the account with an amount of money and returns a string
public String credit(Integer anAmount) {
balance += anAmount;
// return "Account number " + accountNumber + " Has been credited with "+anAmount + " kr.";
return " " + anAmount + " kr has been deposited to " + accountNumber + "\n";
}
public boolean canDebit(Integer anAmount) {
return anAmount <= balance;
}
public String debit(Integer anAmount) {
if (this.canDebit(anAmount)) {
balance -= anAmount;
return " " + anAmount + " kr has been withdrawn from " + accountNumber + "\n";
} else {
return "Account number" + accountNo + "has insufficient funds to debit"
+ anAmount;
}
}
public void addNewAccount(Customer customer) {
accounts.add(new Account(customer, 0));
lastAcc = accounts.get(accounts.size() - 1);
System.out.println("*** New account created. ***" //+ lastAcc
+ "\n");
}
public String removeAccount(int accountNumber) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
found = true; //there is a match stop the loop
if (account.getBalance() == 0) {
iter.remove();//remove this account object
results = "Account number " + accountNumber + " has been removed";
} else {
results = "Account number " + accountNumber + " cannot be removed"
+ "as it has a balance of: " + account.getBalance();
}
}//ends if there is a match
}// end while loop
if (!found) {
results = "No such account";
}
return results;
}
public String creditAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.credit(anAmount);
found = true;//stop the loop
}
}
if (!found) {
results = "No such customer";
}
return results;
}
public String debitAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.debit(anAmount);
found = true;
}
}
if (!found) {
results = "No such Customer";
}
return results;
}
public String getAccountNumbersFor(String CustomerName) {
String details = CustomerName + " has the followinng accounts: "
+ "\n\n";
Iterator iter = accounts.iterator();
//visit all of the accounts in the ArrayList
while (iter.hasNext()) {
Account account = (Account) iter.next();
if (account.getOwner().equals(CustomerName)) {
details += " Account number " + account.getAccountNo()
+ " Balance " + account.getBalance() + "kr \n";
}//ends if
}//ends while
return details;
}
public String bankAccounts() {
String details = "ALL BANK ACCOUNTS" + "\n"
+ "-----------------" + '\n';
if (accounts.size() == 0) {
details += "There are no bank accounts";
} else {
Iterator iter = accounts.iterator();
while (iter.hasNext()) {
details += iter.next().toString() + '\n';
}
}
return details;
}
#Override
public String toString() {
return "Account " + accountNumber + ": " + owner
+ "\nBalance: " + balance + " kr.\n";
}
public Boolean authenticateUser(String login, String ssn) {
if (Luhn.checkLogin(ssn)) {
System.out.println("User authenticated");
return true;
} else {
System.out.println("Authentication refused");
return false;
}
}
public void addAccAr(Account myAccount) {
myAccounts.add(myAccount);
}
public Long getBalanceToLong() {
long balTemp = balans;
return balTemp;
}
public Long getPnTorLong() {
return persnr;
}
public Long getAccNoLong() {
long accTemp = accountNumber;
return accTemp;
}
public ArrayList<Long> getAllAccounts() {
ArrayList<Long> allAccounts = new ArrayList<>();
System.out.println("ALL ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
allAccounts.add(myAccount.getAccNoLong());
allAccounts.add(myAccount.getPnTorLong());
allAccounts.add(myAccount.getBalanceToLong());
}
return allAccounts;
}
/*
public ArrayList<String> getMyAccounts() {
ArrayList<String> ownAccounts = new ArrayList<>();
System.out.println("MY ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
ownAccounts.add(myAccount.getAccNoStr());
ownAccounts.add(myAccount.getBalanceToStr());
}
return ownAccounts;
}*/
}
This is our Customer class
package bank6;
import java.util.ArrayList;
public class Customer {
int custCounter;
//attribut
private Long socialNo;
private String name;
private ArrayList customers;
public Integer customerNumber;
static Integer custNo = 1;
private ArrayList<Customer> clients = new ArrayList<Customer>();
//konstruktor
public Customer(String socialStr, String name) {
Long socialTemp = new Long(socialStr);
this.name = name;
this.socialNo = socialTemp;
customerNumber = custNo++;
}//ends konstruktor customer6
public Customer() {
customers = new ArrayList();
}
/* Set methods*/
public void setName(String name) {
this.name = name;
}
public void setsocialNo(Long socialNo) {
this.socialNo = socialNo;
}
/* get methods */
public String getName() {
return name;
}
public String getSocialNoStr() {
String socialTemp = Long.toString(socialNo);
return socialTemp;
}
public Long getSocialNo() {
return socialNo;
}
/*toString() method*/
#Override
public String toString() {
return "\n" + "Owner: " + name + " (" + socialNo + ")";
}
public void addAccCustAr() {
}
public void addCustomerAr(Customer client) {
clients.add(client);
}
public ArrayList<String> getAllClients() {
ArrayList<String> allClients = new ArrayList<>();
System.out.println("ALL CLIENTS\n-----------");
for (Customer client : clients) {
allClients.add(client.getName());
allClients.add(client.getSocialNoStr() + "\n");
}
return allClients;
//add account
//public void addAccount(account6 account){
// accounts.add(account);
//}// ends adds account
//remove account
//public void removeAccount (account6 account) {
// accounts.remove(account);
//}//ends remove account
}
}//ends public class
This is our Luhn class
package bank6;
public class Luhn {
public static boolean checkLogin(String pnr) {
if (pnr.length() != 10) {
System.out.println("");
return false;
} else {
int length = pnr.length();
int sum = 0;
int pos = length - 1;
for (int i = 1; i <= length; i++, pos--) {
char tmp = pnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0) {
produkt = num * 1;
} else {
produkt = num * 2;
}
if (produkt > 9) {
produkt -= 9;
}
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt) {
System.out.println("Correct");
return true;
} else {
System.out.println("Invalid");
return false;
}
}
}
}
Your Account class already has a Customer field -- good.
You should give Customer an ArrayList<Account> accounts field.
And also give Customer addAccount(Account acct) and removeAccount(Account acct) methods.
Why does Customer have an ArrayList<Customer> field? That makes little sense. Should a Customer hold a list of other Customers? Why? For what purpose?
Why does Account have private ArrayList<Account> myAccounts = new ArrayList<Account>();? That also makes little sense. Should an Account hold a bunch of other Accounts? Again, for what purpose?
The Account class should logically represent one and only one Account.
Same for the Customer class -- it should logically represent only one Customer.
If you think through things logically, they usually come together, and each component of your code should make sense. If it doesn't, question why it is there.
So this code is broken:
Account bank = new Account();
//....
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
Since you're adding a bunch of Customer's to an Account object. It looks like you should have another class, a Bank class, one that can hold an ArrayList<Customer>. Wouldn't this make sense?

Categories