driver class what to do (array) - java

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
);
}
}

Related

Out of bounds exception for my quicksort method

When i pass the value to my quick sort method it intialls sets the pivot to the list size but after going through the loop every value gets reset to zero and throws an out of bounds exception.
This is the method in question
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
This is the rest of the program
import java.io.IOException;
import java.util.*;
import java.util.HashMap;
import java.time.LocalDate;
public class BankingSystem {
private int option = 0;
int key;
Double newAccBalance;
String transType;
Double transAmount;
ArrayList<Transaction> list = new ArrayList<>();
HashMap<Integer, Account> accounts = new HashMap<>();
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException, InputMismatchException{
BankingSystem bankingSystem = new BankingSystem();
bankingSystem.mainLoop();
}
public void mainLoop() {
option = 0;
while (option != 6) {
display();
option = getKeyboardInteger(keyboard);
if (option == 1) {
createAccount();
} else if (option == 2) {
showAccounts();
} else if (option == 3) {
transaction();
} else if (option == 4) {
deleteAccount();
} else if (option == 5) {
showTransactions();
}
}
}
void display(){
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Main Menu-------------------------------|
---------------------------------------------------------------|
Please select option |
1. Create Account |
2. Display Accounts |
3. Deposit/Withdraw |
4. Delete Account |
5. View Transactions |
6. Exit Program |
---------------------------------------------------------------|
>""");
}
public void createAccount() {
System.out.print("""
---------------------------------------------------------------|
------------------------Create Account Menu--------------------|
---------------------------------------------------------------|
1. Create Account |
2. Return to Main Menu |
""");
while (option == 1 && option !=2) {
System.out.print("Please enter the new account number > ");
int accNum = getKeyboardInteger(keyboard);
System.out.print("Please enter the name of the account holder > ");
String accName = getKeyboardString(keyboard);
System.out.print("Please enter the address of the account holder>> ");
String accAdd = getKeyboardString(keyboard);
System.out.print("Please enter the starting balance: ");
Double accOpBalance = getKeyboardDouble(keyboard);
LocalDate accOpDate = LocalDate.now();
System.out.print("Account open date: " + accOpDate);
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
accounts.put(accNum, newAccount);
System.out.print("*Account " + accNum + " added to database* "+ "\n" + ">");
option = getKeyboardInteger(keyboard);
}
}
public void showAccounts() {
option = 0;
while (option == 1 || option != 2){
System.out.print("""
---------------------------------------------------------------|
-----------------------Show Account Menu-----------------------|
---------------------------------------------------------------|
1. View all Accounts |
2. Return to Main Menu |
>""");
option = getKeyboardInteger(keyboard);
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
System.out.println("---------------------------------------------------------------|");
}
}
}
public void deleteAccount(){
int key;
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Delete Menu-----------------------------|
---------------------------------------------------------------|
1. Delete Account |
2. Main Menu |
>""");
while(option != -1) {
System.out.print("""
Select Account Number
>""");
key = getKeyboardInteger(keyboard);
accounts.remove(key);
option = getKeyboardInteger(keyboard);
}
}
public void transaction(){
option = 0;
while(option != 3){
System.out.println("""
---------------------------------------------------------------|
-----------------------Transaction Menu------------------------|
---------------------------------------------------------------|
Please select the type of transaction:
1. Deposit
2. Withdraw
3. Main Menu""");
option = getKeyboardInteger(keyboard);
switch(option){
case 1 -> {
doDeposit();
break;
}
case 2 -> {
doWithdrawal();
break;
}
}
}
}
public void doWithdrawal(){
transType = "Withdrawal";
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
System.out.print("How Much would you like to withdraw > ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount > getBalance) {
System.out.println("Insufficient funds");
}else{
newAccBalance = getBalance - transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void doDeposit(){
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
transType = "Deposit";
System.out.print("How Much would you like to deposit? ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount <= 0) {
System.out.print("Please enter a positive value!");
}else {
newAccBalance = getBalance + transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void showTransactions() {
option = 0;
key = getKeyboardInteger(keyboard);
list = accounts.get(key).transList;
myQuickSort(list);
while(option != 2) {
System.out.print("""
---------------------------------------------------------------|
-------------------Show Transactions Menu----------------------|
---------------------------------------------------------------|
1.View Transactions
2.Main Menu
>""");
for(int i = 0; i < accounts.get(key).transList.size(); i++){
System.out.print(accounts.get(key).transList.get(i));
}
option = getKeyboardInteger(keyboard);
}
}
public String getKeyboardString(Scanner keyboard){
while (true){
try{
return keyboard.next();
}catch(Exception e){
keyboard.next();
System.out.print("Something went wrong! Please try again" + "\n> ");
}
}
}
public int getKeyboardInteger(Scanner keyboard){
while(true){
try{
return keyboard.nextInt();
}catch(Exception e){
keyboard.next();
System.out.print("Not an option! Please enter a valid option" + "\n> ");
}
}
}
public Double getKeyboardDouble(Scanner Double){
while(true){
try{
return keyboard.nextDouble();
}catch (Exception e){
keyboard.next();
System.out.print("Not an option! Enter an Integer or Decimal value" + "\n>");
}
}
}
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
}
import java.time.LocalDate;
import java.util.ArrayList;
public class Account{
private int accNum;
private String accName;
private String accAdd;
private LocalDate accOpDate;
private Double accOpBalance;
public ArrayList<Transaction> transList;
public Account(int accNum, String accName, String accAdd, LocalDate accOpDate, Double accOpBalance){
setAccNum(accNum);
setAccName(accName);
setAccAdd(accAdd);
setAccOpDate(accOpDate);
setAccOpBalance(accOpBalance);
transList = new ArrayList<Transaction>();
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public void setAccOpDate(LocalDate accOpDate){
this.accOpDate = accOpDate;
}
public void setAccOpBalance(Double accOpBalance){
this.accOpBalance = accOpBalance;
}
public Double getAccOpBalance(){
return accOpBalance;
}
#Override
public String toString() {
return "\n" + "Account Number: " + accNum + "\n" + "Name: " + accName +
"\n" + "Account Holder Address: " + accAdd + "\n" +"Account open date: "
+ accOpDate + "\n" + "Account balance: " + accOpBalance;
}
}
import java.util.ArrayList;
public class Transaction extends ArrayList implements Comparable<Transaction> {
private Double transAmount;
private String transType;
public Transaction(Double transAmount, String transType){
this.transAmount = transAmount;
this.transType = transType;
}
public void setTransAmount(Double transAmount){
this.transAmount = transAmount;
}
public String getTransType(){
return transType;
}
public void setTransType(String transType){
this.transType = transType;
}
public Double getTransAmount(){
return transAmount;
}
#Override
public int compareTo(Transaction compareAcc){
if(this.transAmount < compareAcc.transAmount)
return -1;
else if (compareAcc.transAmount < this.transAmount)
return 1;
return 0;
}
#Override
public String toString() {
return "\n" + "Transaction type: " + transType +
"\n" + "Amount: " + transAmount + "\n";
}
}
Ive tried running through the code step by step in intellij but cant quite figure it out.
Well, I'd like to make this quick and easy to understand. The problem here is that it recurses infinitely. Everytime it reaches the
lesser = myQuickSort(lesser);
line is recurses. And keep in mind that the list parameter this method receives shrinks in size every time it recurses. Because, for example, the first time you give it a list of size 100 then it gets sorted into lesser/greater and then lesser invokes the method again and it recurses again but this time the arraylist given as the parameter is less than the first. Until it reaches a point where the list has pivot = 0 in it and when it's done sorting that it recurses for one final time and attempts to run this line of code.
Transaction pivot = list.get(list.size()-1);
Which attempts to get the Transaction at the -1 index since the list at this point is empty so the size = 0. This causes an ArrayIndexOutOfBoundsException.
This is a very problematic method and also keep in mind that you probably need a base case to stop it from recurring infinitely and also a few improvements in general.
Hope this helps.
Edit: also due to the infinite recursion this method could cause a stackoverflow error

What is wrong with the constructor? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am supposed to design an inventory system that will store specific products using the provided Driver class named ProductTester to test my program. But for some reason, it doesn't work. When I look at the problem on the program, it states that I'm using the wrong data type on the constructor in ProductTester. But from what I see, I think I'm using it correctly?
Screenshot of the problem.
On the log, I couldn't really understand the problem, but the description states:
'CD(java.lang.String, double, int, int, java.lang.String, int, java.lang.String)' in 'Project10.CD' cannot be applied to '(int, java.lang.String, int, double, java.lang.String, int, java.lang.String)'
'CD(java.lang.String, double, int, int, java.lang.String, int, java.lang.String)' in 'Project10.CD' cannot be applied to '(int, java.lang.String, int, double, java.lang.String, int, java.lang.String)'
'CD(java.lang.String, double, int, int, java.lang.String, int, java.lang.String)' in 'Project10.CD' cannot be applied to '(int, java.lang.String, int, double, java.lang.String, int, java.lang.String)'
Sorry, I was only able to provide you with partial of the code because I wasn't able to finish the other part. So please ignore some of the parts that have missing details. For example DVD.
public class Product {
private int number;
private String name;
private double price;
private int quantity;
private boolean active = true;
public Product(int number, String name, double price, int quantity) {
setNumber(number);
setName(name);
setProductPrice(price);
setQtyInStock(quantity);
}
public int getNumber() { return number; }
public void setNumber(int number) { this.number = number; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getProductPrice() { return price; }
public void setProductPrice(double price) { this.price = price; }
public int getQuantity() { return quantity; }
public void setQtyInStock(int quantity) { this.quantity = quantity; }
public void addToInventory(int quantity) { this.quantity += quantity; }
public void deductFromInventory(int quantity) { if (!(this.quantity - quantity < 0)) this.quantity -= quantity; }
public void setActive(boolean active) { this.active = active; }
public String toString() {
return "\nItem Number: " + getNumber() + "\nName: " + getName() + "\nQuantity in Stock: " + getQuantity()
+ "\nPrice: " + getProductPrice() + "\nStock Value: " + (quantity * price) + "\nProduct Status: "
+ (this.active?"Active" : "Discontinued");
}
}
class CD extends Product {
private String artist;
private int numOfSongs;
private String label;
private boolean active = true;
public CD(String name, double price, int quantity, int number, String artist, int numOfSongs, String label) {
super(number, name, price, quantity);
setArtist(artist);
setNumberOfSongs(numOfSongs);
setLabel(label);
}
public String getArtist() { return this.artist; }
public void setArtist(String artist) { this.artist = artist; }
public int getNumberOfSongs() { return this.numOfSongs; }
public void setNumberOfSongs(int numOfSongs) { this.numOfSongs = numOfSongs; }
public String getLabel() { return this.label; }
public void setLabel(String label) { this.label = label; }
public String toString() { // Overriding the toString method to display it's own stuff
return "\nItem Number: " + getNumber() + "\nName: " + getName() + "\nArtist: " + getArtist()
+ "\nSongs on Album: " + getNumberOfSongs() + "\nRecord Label: " + getLabel() + "\nQuantity in Stock: " + getQuantity()
+ "\nPrice:" + getProductPrice() + "\nStock Value: " + (getQuantity() * getProductPrice())
+ "\nProduct Status: " + (this.active ? "Active" : "Discontinued");
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class ProductTester {
public static void main(String[] args) {
//create a Scanner object for keyboard input
Scanner in = new Scanner(System.in);
int maxSize, menuChoice;
maxSize = getNumProducts(in);
if(maxSize == 0) {
//Display a no products message if zero is entered
System.out.println("No products required!");
}else {
Product[] products = new Product[maxSize];
addToInventory(products, in);
do {
menuChoice = getMenuOption(in);
executeMenuChoice(menuChoice, products, in);
}while(menuChoice != 0);
}//endif
}//end method main
static void executeMenuChoice(int choice, Product[] products, Scanner in) {
switch(choice) {
case 1: System.out.println("View Product List");
displayInventory(products);
break;
case 2: System.out.println("Add Stock");
addInventory(products, in);
break;
case 3: System.out.println("Deduct Stock");
deductInventory(products, in);
break;
case 4: System.out.println("Discontinue Stock");
discontinueInventory(products, in);
break;
}//end switch
}//end method executeMenuChoice
static void discontinueInventory(Product[] products, Scanner in) {
int productChoice;
productChoice = getProductNumber(products, in);
products[productChoice].setActive(false);
}//end method deductInventory
static void deductInventory(Product[] products, Scanner in) {
int productChoice;
int updateValue = -1;
productChoice = getProductNumber(products, in);
do {
try {
System.out.print("How many products do you want to deduct? ");
updateValue = in.nextInt();
if(updateValue <0)
System.out.println("Please only enter positive values to deduct stock");
//endif
if(updateValue > products[productChoice].getQuantity())
System.out.println("THere is not enough stock to remove that amount, only "
+ products[productChoice].getQuantity() + " left!");
}catch(InputMismatchException e) {
System.out.println("Incorrect data type entered!");
in.nextLine();
}catch(Exception e) {
System.out.println(e);
in.nextLine();
}
}while(updateValue < 0 ||updateValue > products[productChoice].getQuantity());
products[productChoice].deductFromInventory(updateValue);
}//end method deductInventory
static void addInventory(Product[] products, Scanner in) {
int productChoice;
int updateValue = -1;
productChoice = getProductNumber(products, in);
do {
try {
System.out.print("How many products do you want to add? ");
updateValue = in.nextInt();
if(updateValue <0)
System.out.println("Please only enter positive values to add stock");
//endif
}catch(InputMismatchException e) {
System.out.println("Incorrect data type entered!");
in.nextLine();
}catch(Exception e) {
System.out.println(e);
in.nextLine();
}
}while(updateValue < 0);
products[productChoice].addToInventory(updateValue);
}//end method addInventory
static int getProductNumber(Product[] products, Scanner in) {
int productChoice = -1;
//display the contents of the products array
for(int i = 0; i< products.length; i++)
System.out.println(i + " : " + products[i].getName());
do {
try {
System.out.print("Please enter the item number of the product you want to update: ");
productChoice = in.nextInt();
if(productChoice < 0 || productChoice > products.length -1)
System.out.println("Please only enter values between 0 and "
+ (products.length -1));
//endif
}catch(InputMismatchException e) {
System.out.println("Incorrect data type entered!");
in.nextLine();
}catch(Exception e) {
System.out.println(e);
in.nextLine();
}
}while(productChoice < 0 || productChoice > products.length -1);
return productChoice;
}//end method getProductNumber
static int getMenuOption(Scanner in) {
int menuOption = -1;
//display the menu until a valid input is provided
do {
try {
System.out.println("\n\n1. View Inventory\n2. Add Stock\n3. Deduct Stock\n"
+ "4. Discontinue Product\n0. Exit");
System.out.print("Please enter a menu option: ");
menuOption = in.nextInt();
}catch(InputMismatchException e) {
System.out.println("Incorrect data type entered!");
in.nextLine();
}catch(Exception e) {
System.out.println(e);
in.nextLine();
}
}while(menuOption < 0 || menuOption > 4);
//return the valid input from the user
return menuOption;
}//end method getMenuOption
static int getNumProducts(Scanner in) {
int maxSize= -1;
//prompt the user until they enter a number >= zero
do {
try{
//display prompt to user
System.out.println("Enter the number of products you would like to add.");
System.out.print("Enter 0 (zero) if you do not wish to add products: ");
//assume that the user enters a valid
maxSize = in.nextInt();
if(maxSize < 0)
System.out.println("Incorrect Value entered");
//endif
}
catch(InputMismatchException e) {
System.out.println("Incorrect data type entered!");
in.nextLine();
}catch(Exception e){
System.out.println(e);
in.nextLine();
}
}while(maxSize < 0);
//returns the valid value entered by the user
return maxSize;
}//end method getNUmProducts
static void addToInventory(Product[] products, Scanner in) {
//create local variables
int stockChoice = -1;
for(int i = 0; i < products.length; i++) {
//display the menu until a valid input is provided
do {
try {
//ask the user to enter the product information
System.out.println("\n1: CD\n2: DVD");
System.out.print("Please enter the product type: ");
stockChoice = in.nextInt();
if(stockChoice < 1 || stockChoice > 2)
System.out.println("Only numbers 1 or 2 allowed!");
//endif
}catch(InputMismatchException e) {
System.out.println("Incorrect data type entered!");
in.nextLine();
}catch(Exception e) {
System.out.println(e);
in.nextLine();
}
}while(stockChoice < 1 || stockChoice > 2);
if(stockChoice == 1)
addCDToInventory(products, in, i);
else
addDVDToInventory(products, in, i);
}
}//end method addToInventory
static void addCDToInventory(Product[] products, Scanner in, int i) {
//create local variables
int number;
String name;
int quantity;
double price;
String artist;
int numOfSongs;
String label;
//clear the input buffer
in.nextLine();
//ask the user to enter the product information
System.out.print("\n\nPlease enter the CD name: ");
name = in.nextLine();
System.out.print("Please enter the artist name: ");
artist = in.nextLine();
System.out.print("Please enter the record label name: ");
label = in.nextLine();
System.out.print("Please enter the number of songs: ");
numOfSongs = in.nextInt();
System.out.print("Please enter the quantity of stock for this product: ");
quantity = in.nextInt();
System.out.print("Please enter the price for this product: ");
price = in.nextDouble();
System.out.print("Please enter the item number: ");
number = in.nextInt();
//create a CD product object and store it in the products array
products[i] = new CD( number, name, quantity, price, artist, numOfSongs, label);
}//end method addCDToInventory
static void addDVDToInventory(Product[] products, Scanner in, int i) {
//create local variables
int number;
String name;
int quantity;
double price;
int length;
int rating;
String studio;
//clear the input buffer
in.nextLine();
//ask the user to enter the product information
System.out.print("\n\nPlease enter the DVD name: ");
name = in.nextLine();
System.out.print("Please enter the film studio name: ");
studio = in.nextLine();
System.out.print("Please enter the age rating: ");
rating = in.nextInt();
System.out.print("Please enter the length in minutes: ");
length = in.nextInt();
System.out.print("Please enter the quantity of stock for this product: ");
quantity = in.nextInt();
System.out.print("Please enter the price for this product: ");
price = in.nextDouble();
System.out.print("Please enter the item number: ");
number = in.nextInt();
//create a DVD product object and store it in the products array
products[i] = new DVD(number, name, quantity, price, length, rating, studio);
}//end method addDVDToInventory
static void displayInventory(Product[] products) {
//display the contents of the products array
for(Product product: products)
System.out.println(product);
}//end method displayInventory
}//end class ProductTaster
You get the error because you are trying to pass in unexpected parameters.
The constructor of your CD class looks like this:
public CD(String name, double price, int quantity, int number, String artist, int numOfSongs, String label) {
super(number, name, price, quantity);
setArtist(artist);
setNumberOfSongs(numOfSongs);
setLabel(label);
}
So it expects:
String name, double price, int quantity, int number, String artist, int numOfSongs, String label
but you are passing in:
int number, String name, int quantity, double price, String artist, int numOfSongs, String label
To fix this, change the constructor to take in the correct parameters you want.

Search arraylist of objects does not work

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

May someone help me check how to create a list?

guys, am doing java programing and try to make a list, but i cannnot let it work as i expected, please help me find out where is wrong.
i have create the code on BlueJ and try to make main and method in different part, but when i try to add a variable in list, it seems added but wont present correctly, and remove method will call error and shut down the whole program
one is :
import java.util.ArrayList;
public class Plane
{
//Create 3 types of variables.
private String name;
private int safelength;
private short station;
private String passengername;
private static int seat;
private static int age;
private ArrayList<Passenger> Passengers;
public Plane(String psgname, int psgseat, int psgage)
{
psgname = passengername;
psgseat = seat;
psgage = age;
Passengers = new ArrayList<Passenger>();
}
public Plane(String planename, int maxlength, short astation)
{
name = planename;
safelength = maxlength;
station = astation;
}
public void addPassenger(Passenger Passenger)
{
Passengers.add(Passenger);
}
public void addPassenger(String passengernames, int pseat, int page)
{
Passengers.add(new Passenger(passengername, seat, page));
}
public Passenger findPassenger(String find)
{
for(Passenger ps : Passengers)
{
if(ps.getpname().contains(find))
{
return ps;
}
}
return null;
}
public int numberofPassenger()
{
return Passengers.size();
}
public void removePassenger(int number)
{
if (number >= 0 && number <numberofPassenger())
{
Passengers.remove(number);
}
}
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
public void setname(String n)
{
name = n;
}
public String getname()
{
return name;
}
public void setsafelength(int s)
{
safelength = s;
}
public int getsafelength()
{
return safelength;
}
public void setstation(short a)
{
station = a;
}
public short getstation()
{
return station;
}
public String toString()
{
String text = "System checked, " + getname() + ", you can prepare yourself at station " + getstation() + " with the maxlength of " + getsafelength() + " metres.";
return text;
}
}
another one is :
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private static String pname;
private static int seat;
private static int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(pname, seat, age);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public static void setpname(String pn)
{
pname = pn;
}
public static String getpname()
{
return pname;
}
}
Problem 1.
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
Here you are printing the value of instance variable,not the passenger's name.To print it, do
System.out.println(Passengers.get(index).getpname());
but this will return null,because your pname is static and you have never initialized its value.For this,change all yor static varibales to non-static.
Problem 2.
Passenger padd = new Passenger(pname, seat, age);
you are storing passenger's name seat age in x y zvariables respectively,butduring the creation of Passenger ,you are using pname seat age variables, which are null.So here do
Passenger padd = new Passenger(x, y, z);
At last,change every static variable and methods to non-static.
Final Solution will look like this,
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private String pname;
private int seat;
private int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(x, y, z);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public void setpname(String pn)
{
pname = pn;
}
public String getpname()
{
return pname;
}
}

Why is my program not accepting input through the console? (Java)

I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.
The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.
you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once

Categories