My Exception is not working - java

I am creating 3 things right now; a driver, a class and an exception.
Currently having trouble with my book store class recognizing the exceptions on my book class.
What am I doing wrong?
Driver: edited by the given suggestion by #Satoshi Kouno
import java.io.*;
import java.util.*;
public class BookStore{
public static void main(String arg[ ]) throws Exception{
Scanner sc = new Scanner(System.in);
int isbn=0;
int quantity = 0;
String title = "";
Book oneBook;
boolean exit = false;
List<Book> bookList = new ArrayList<Book>(); //here
while(true){
try{
sc = new Scanner(System.in);
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();
// Validation Codes
// Condition
if(isbn !=0 && quantity != 0 && !"".equals(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;
}
}
catch(InputMismatchException ime){
System.out.println("you did not enter a number");
}
catch (BookException be){
System.out.println(be.getMessage( )); //
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
} //main method
} //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 Exception{
//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;
}
}
}
And my exception class: edited #2
public class BookException extends Exception {
//instance variable
private String message = "";
public BookException(String message) {
super(message);
}
public void setMessage(String newMessage) {
this.message = newMessage;
}
public String getMessage() {
return this.message;
}
}
Trying to get my class to work with my driver but it's not working.
EDIT!! PSA
i forgot to point out the requirements of my driver class
Read the book title from the user
Read the book ISBN from the user
Read the book in stock quantity from the user
Your 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.
Your 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.
my book and exception class are not needed changes already
they just want me to make my own driver to run with both of them and their exceptions

Your class is not working to due this:
// Validation Codes
// Condition
if(isbn !=0 && quantity != 0 && title != null && title != "")
 
title != ""
This condition will be never and never verified so will not enter in the part of code where you create the Book object:
To compare String values just replace it by:
!"".equals(title);
#See String#equals() JavaDOC
or use apache lang classes (probably you will have to import it):
StringUtils.isNotEmpty(title);
Moreover:
I suggest you to modify your custom exception class adding the construct:
public class BookException extends Exception {
public BookException(String message) {
super(message);
}
}
And in Book#setTitle and the other one setters raise it by:
throw new BookException("Title cannot be blank!");
Hope this help.
Update:
Analysing the code i checked others things like:
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
} else {
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
This check is wrong for me, probably you wanted to do this:
isbn >= 1000 && isbn <= 10000

Related

Variable cannot be resolved error in Java

I know this is a very very common error but I am stuck on this one and I totally don't understand why is it happening.
Here is a part of my code
import java.util.ArrayList;
import java.util.Scanner;
public class Manager {
private static Scanner sc = new Scanner(System.in);
protected static ArrayList<String> identifications = new ArrayList<String>();
protected static String[] signIn() {
System.out.println("Hi !");
System.out.println("Welcome to School Management System");
System.out.print("Please enter your ID number : ");
boolean idValid = false;
String providedID = null;
int idListPosition = -1;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
while (idValid != true) {
for (String element : identifications) {
if (element.equals(providedID)) {
idValid = true;
idListPosition = identifications.indexOf(element);
break;
}
}
if (idValid && idListPosition != -1) {
System.out.println("Welcome !");
String[] returnValue = {"true", identifications.get(idListPosition), identifications.get(idListPosition + 1), identifications.get(idListPosition + 2)};
return (returnValue);
} else {
System.out.println("Error : the ID you entered does not exist. Please try again");
providedID = null;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
}
}
}
public static void main(String[] args) {
init();
String[] response = signIn();
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}
protected static void init() {
identifications.add("056789");
identifications.add("teacher");
identifications.add("Temperson");
}
}
The Teacher and Student classes are empty for now. I just made them use the super constructor of their parent class Person :
public class Person {
String type;
String name;
String idNumber;
public Person(String idnumber, String newType, String providedName) {
this.idNumber = idnumber;
this.type = newType;
this.name = providedName;
}
protected String[] showInfos() {
String[] returnValue = {this.type, this.name, this.idNumber};
return returnValue;
}
}
But I get user cannot be resolved to a variable and user cannot be resolved error.
Normally the code that needs user will never run unless sign in has completed. And since sign in never ends before a correct ID is entered, the user variable will always be assigned to a a value.
Thanks for helping !
The scope of the user object is limited to the if condition, hence you are getting this error.
If Teacher and Student extends Person then you can try this piece of code:
public static void main(String[] args) {
init();
String[] response = signIn();
Person user = null;
if (response[2].equals("teacher")) {
user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}
You're having a Scope problem here:
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
Variables declared in a if block are local to that if block. You can see this in it's simplest form with an example like this:
if(true) {
String value = "Out of Scope";
}
System.out.println(value); //value cannot be seen outside the if block
You will need to declare your Teacher and/or Student variable outside the if block if you wish to use them after the block (this is where using your inheritance class would come in handy). Using the previous example:
boolean someCondition = true;
String value;
if(someCondition) {
value = "In Scope - True";
} else {
value = "In Scope - False";
}
System.out.println(value); //value can now be seen
You have declared 2 different versions of user, so the print statement can't know which you mean. Or it couldn't if it could see either, but since each is declared inside of its own block, the print doesn't see either of them.

Java program not saving object to HashMap

Either my save_product function in my Repository.java class doesn't save correctly into the map product_repository or, maybe it does save, but I'm not outputting it correctly in my find_product function in my Repository.java class. I think I'm using the correct function to search for the value in the map, .get
I experimented with product_repository.keySet().iterator().forEachRemaining(System.out::println); but that's the first time I ever used that... also please forgive how I insert the keyinto the map product_repository in the create_new_product function in the Controller.java class. I'm new to java ...
Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
Product.java
package com.company;
public class Product {
private String product_name;
private String product_brand;
private int product_cost;
private int product_count;
private boolean product_availability;
public Product() {
}
public Product(String product_name, String product_brand,
int product_cost, int product_count, boolean product_availability) {
this.product_name = product_name;
this.product_brand = product_brand;
this.product_cost = product_cost;
this.product_count = product_count;
this.product_availability = product_availability;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_brand() {
return product_brand;
}
public void setProduct_brand(String product_brand) {
this.product_brand = product_brand;
}
public int getProduct_cost() {
return product_cost;
}
public void setProduct_cost(int product_cost) {
this.product_cost = product_cost;
}
public int getProduct_count() {
return product_count;
}
public void setProduct_count(int product_count) {
this.product_count = product_count;
}
public boolean isProduct_availability() {
return product_availability;
}
public void setProduct_availability(boolean product_availability) {
this.product_availability = product_availability;
}
}
Controller.java
package com.company;
import java.util.Scanner;
public class Controller {
private static Long key;
public static void create_new_product(){
Repository repository = new Repository();
//Supplier supplier = new Supplier();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
key = 0L;
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
key++;
repository.save_product(key, product);
}
public void search_product(){
Repository repository = new Repository();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
repository.find_product(id);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
repository.find_product(name);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
Repository.java
package com.company;
import java.util.HashMap;
import java.util.Map;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap){
try{
if (product_repository.containsValue(newProductMap)) {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
else {
product_repository.put(key, newProductMap);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public void find_product(Long key){
try {
if (product_repository.containsKey(key)) {
System.out.println(product_repository.get(key));
}
else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
// Overload
public void find_product(String name) {
try {
if (product_repository.containsValue(name)) {
System.out.println(product_repository.get(name));
product_repository.keySet().iterator().forEachRemaining(System.out::println);
}
else {
System.out.println("No matches were found for product name: " + name);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
}
You have to make Repository repository a field of your Controller class. You are currently throwing the repositories away after your methods create_new_product and search_product have executed. Therefore you need to remove the first line of each of these methods.
Another problem is inside your find_product(String name) method where your call product_repository.get(name) but name is a String and the get method expects an ID, i.e. a Long so this call will always return null.
As it was pointed out before the repository has to be made global. However, the entire code is a bit messy. You are searching for a product id but the id is not shown to you. It is like searching for database records but the ids are autogenerated. Good luck with that. So I would suggest to allow this program to enter the id as well. It makes much more sense if you want to search for the id.
Otherwise, if you are interested in only the value, id can be taken out.
Below you can find the modified code that works for all the methods.
//main stays the same
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
//controller is a bit changed. Added global repository and improved the search.
import java.util.Collection;
import java.util.Scanner;
public class Controller {
private static Long key;
Repository repository = new Repository();
public void create_new_product() {
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product id: ");
long id = Long.parseLong(scanner.nextLine());
product.setProductId(id);
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
repository.save_product(id, product);
}
public void search_product() {
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
Product product = repository.find_product(id);
try {
if (product.getProduct_count() > 0) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
} else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
Collection<Product> products = repository.find_products(name);
if (products.size() > 0) {
for (Product product : products) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} else {
System.out.println(" out of stock.");
}
} else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
//Added a new field to the Repository so you can also search by key.
import java.util.*;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap) {
try {
if (!product_repository.containsKey(key)) {
product_repository.put(key, newProductMap);
} else {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public Product find_product(final Long key) {
try {
if (product_repository.containsKey(key)) {
System.out.println("Found product: " + product_repository.get(key).getProduct_name());
return product_repository.get(key);
} else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
return null;
}
// Overload
public Collection<Product> find_products(final String name) {
Collection<Product> values = new ArrayList<>();
for (Map.Entry<Long, Product> productEntry : product_repository.entrySet()) {
if (productEntry.getValue().getProduct_name().equals(name)) {
System.out.println("matches were found for product name: " + name);
values.add(productEntry.getValue());
}
}
return values;
}
}

How to add user input into an array

This is the parent class
public class Holding {
private String holdingId, title;
private int defaultLoanFee, maxLoanPeriod, calculateLateFee;
public Holding(String holdingId, String title){
this.holdingId = holdingId;
this.title = title;
}
public String getId(){
return this.holdingId;
}
public String getTitle(){
return this.title;
}
public int getDefaultLoanFee(){
return this.defaultLoanFee;
}
public int getMaxLoanPeriod(){
return this.maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the child class:
public class Book extends Holding{
private String holdingId, title;
private final int defaultLoanFee = 10;
private final int maxLoanPeriod = 28;
public Book(String holdingId, String title){
super(holdingId, title);
}
public String getHoldingId() {
return holdingId;
}
public String getTitle(){
return title;
}
public int getDefautLoanFee(){
return defaultLoanFee;
}
public int getMaxLoanPeriod(){
return maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getHoldingId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the menu:
public class LibraryMenu {
static Holding[]holding = new Holding[15];
static int hold = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int options = keyboard.nextInt();
do{
}
System.out.println();
System.out.println("Library Management System");
System.out.println("1. Add Holding");
System.out.println("2. Remove Holding");
switch(options){
case 1:
addHolding();
break;
default:
System.out.println("Please enter the following options");
}
}while(options == 13);
System.out.println("Thank you");
}
public static void addHolding(){
System.out.println("1. Book");
System.out.println("2. Video");
int input1 = input.nextInt();
switch(input1){
case 1:
addBook();
break;
case 2:
addVideo();
break;
default:
System.out.println("Please select the following options");
break;
}
}
public static void addBook(){
}
}
All i want is when a user wants to add a book, the user will type in the title and id for it and it will save into the array, and when it is done, it will go back to the menu. I cant seem to do it with my knowledge at the moment.
i tried to do this in the addBook() method
holding[hold] = new Book();
holding[hold].setBook();
the setBook method would be in the Book class, to complete the setBook, i have to make set methods for all the get method. But when i do this, the constructor is undefined.
public void setBook(){
System.out.println("Title: " + setTitle());
System.out.println("ID: " + setHoldingId());
System.out.println("Loan fee: " + setDefaultLoanFee());
System.out.println("Max Loan Period: " + setMaxLoanPeriod());
}
If there is anything wrong with my code, please feel free to say it to me :D
Thanks.
edit: After the user adds a book or video, when the user wants to print all the holdings, it will show the title, id, loan fee and max loan period. How do i do that?
edit2: Clean up a few parts that wasn't necessary with my question
I would suggest you to use "List of Object" concept in handling it.
1) You can define a List of Book object for example.
List<Book> bookList = new ArrayList<Book>();
2) Everytime when you hit AddBook() function, you can then do something like this.
//Create a temporary object of Book to get the user input data.
Book tempBook = new Book(holdingIDParam, titleParam);
//Add them to the list
bookList.Add(tempBook);
3) You can then use that list to your likings, whether to store them into a .txt based database or to use them throughout the program. Usage example:
bookList.get(theDesiredIndex).getBook() ...
I am not entirely sure of what you want but after paying focus on your bold text,this is what I can understand for your case. Feel free to correct me on your requirements if it doesn't meet.
Hope it helps :)

Text User Interface, cannot get a method to work

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!

Scanner Input not Reading Method Calling as a Parameter

First of All here's the Codes:
Product Information:
public class ProductInformation
{
public String code;
public String itemName;
public double price;
//Constructor
public ProductInformation()
{ itemName="-";
code="-";
price=0;}
//Setter
public void setItemName(String itemName)
{ this.itemName=itemName;}
public void setCode(String code)
{ this.code=code;}
public void setPrice(double price)
{ this.price=price;}
//Getter
public String getItemName()
{ return itemName;}
public double getPrice()
{ return price;}
public String getCode()
{ return code;}
//Products
public void getProduct(String code)
{ if(code == "A001"){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code == "A002"){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code == "A003"){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code == "A004"){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code == "A005"){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
}
import java.util.*;
Product Display:
public class ProductDisplay
{ public ProductInformation product;
public ProductDisplay()
{
System.out.println("\t\t\t\t RG COMPUTER SHOP");
System.out.println("\t\t\t\t Makati City");
System.out.println("\t\tP R O D U C T\tI N F O R M A T I O N");
System.out.println("-------------------------------------------------------");
System.out.println("\t\tCode\t\tDescription\t\tUnit Price");
System.out.println("-------------------------------------------------------");
product = new ProductInformation();
product.getProduct("A001");
display();
product = new ProductInformation();
product.getProduct("A002");
display();
product = new ProductInformation();
product.getProduct("A003");
display();
product = new ProductInformation();
product.getProduct("A004");
display();
product = new ProductInformation();
product.getProduct("A005");
display();
}
// Display Method
public void display()
{ System.out.println("\t\t" + product.getCode()
+ "\t\t" + product.getItemName()
+ "\t\t" + product.getPrice()); }
}
My Problem is here in PointOfSale
I tried to let the buyer decide by entering a Product Code
after entering the getProduct I get is always "A005" Even if I enter "A001" or something else. I think the product.getProduct(code) is not working out. Can someone help me fix this problem so i can continue scripting this
import java.util.*;
public class PointOfSale extends ProductDisplay
{
public PointOfSale()
{ System.out.print("\nPurchase Item(y/n)?");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
if("y".equalsIgnoreCase(line)){
OpenOrder();
}
}
//=============================================
public void OpenOrder() // New Order
{ ArrayList<String> ProductList = new ArrayList<String>();
ProductList.add("A001"); ProductList.add("A002");
ProductList.add("A003"); ProductList.add("A004");
ProductList.add("A005");
System.out.print("Select Product Code:");
Scanner sc = new Scanner(System.in);
String code = sc.next();
if(ProductList.contains(code))
{ product.getProduct(code);
display(); EnterQuantity(); }
else System.out.print("Product Code is Invalid\n"); System.exit(0);}
//==============================================
public void EnterQuantity() //Entering Quantity
{
try{
System.out.print("Enter Quantity:");
Scanner sc = new Scanner(System.in);
int quantity = sc.nextInt();
double amount = quantity * product.getPrice();
System.out.print("Amount: " + amount);}
catch (InputMismatchException nfe)
{System.out.print("\nInvalid Entry: Input must be a Number.\n"); System.exit(0);}
}
// Main Method
public static void main(String[] args)
{ new PointOfSale(); }
}
You are comparing strings for equality in your getProduct() method. Strings are objects, so you probably want to use the equals() method:
public void getProduct(String code)
{ if(code.equals("A001")){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code.equals("A002")){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code.equals("A003")){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code.equals("A004")){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code.equals("A005")){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
One major problem is that you're comparing Strings using == and you in general shouldn't do that as this compares if one object reference is the same as another and you don't care about this. Instead you care if the two String variables hold the same String representation, and for this use the equals() or equalsIgnoreCase() methods.

Categories