What is wrong with the constructor? [closed] - java

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.

Related

How to access an object parameter from a hashmap value

I am trying to access the accOpBalance parameter from the Account method stored in the HashMap. I want to be able to change this value based on transaction type and store it again. I also want to save the the 6 most recent transactions fot the account but not sure how to approach the problem. I hope this describes the problem well enough. Im still very new to this and would love feedback on my code aswell.
public class BankingSystem{
static int accNum;
static String accName;
static String accAdd;
static String accOpDate;
static double accOpBalance;
int option = 0;
static Scanner keyboard = new Scanner(System.in);
static HashMap<Integer, Account> accounts = new HashMap<Integer, Account>(Map.of(
accNum, new Account(accNum, accName, accAdd, accOpDate, accOpBalance)
));
public BankingSystem() {
}
public static void main(String[] args) {
BankingSystem bankingSystem = new BankingSystem();
int option;
do{
option = mainMenu(keyboard);
System.out.println();
if(option == 1){
bankingSystem.createAccount(keyboard);
} else if (option == 2) {
bankingSystem.showAccounts();
} else if (option == 4) {
bankingSystem.deleteAccount();
}
}while(option != 5);
}
public void createAccount(Scanner keyboard) {
do{
System.out.println("-----------------------------------------------");
System.out.print("Please enter 1 to continue or -1 to exit: ");
option = keyboard.nextInt();
switch (option) {
case 1 -> {
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
System.out.println("-----------------------------------------------");
System.out.print("Please enter the new account number: ");
accNum = keyboard.nextInt();
newAccount.setAccNum(accNum);
System.out.print("Please enter the name of the account holder: ");
accName = keyboard.next();
newAccount.setAccName(accName);
System.out.print("Please enter the address of the account holder: ");
accAdd = keyboard.next();
newAccount.setAccAdd(accAdd);
System.out.print("Please enter the accounts open date: ");
accOpDate = keyboard.next();
newAccount.setAccOpDate(accOpDate);
System.out.print("Please enter the starting balance: ");
accOpBalance = keyboard.nextDouble();
newAccount.setAccOpBalance(accOpBalance);
accounts.put(accNum, new Account(accNum, accName, accAdd, accOpDate, accOpBalance));
}
case 2 -> {
System.out.println("Please type -1 the exit create account menu: ");
option = keyboard.nextInt();
}
}
}while (option != -1);
}
public void showAccounts() {
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
}
}
public void deleteAccount(){
int key;
option = 0;
do {
System.out.println("-----------------------------------------------");
System.out.print("Please enter 1 to continue or -1 to exit: ");
option = keyboard.nextInt();
switch (option) {
case 1 -> {
System.out.print("-----------------------------------------------");
System.out.print("Please enter the Account number of the" + "\n" +
" the account you wish to delete");
System.out.print("-----------------------------------------------");
key = keyboard.nextInt();
accounts.remove(key);
}
case 2 -> {
System.out.println("Please type -1 the exit delete account menu: ");
option = keyboard.nextInt();
}
}
}while (option != -1);
}
public static int mainMenu(Scanner keyboard){
int menuOption;
System.out.println("Welcome to the bank of Cal");
System.out.println("-----------------------------------------------");
System.out.println("Main Menu" + "\n" + "Please select option:");
System.out.println("1. Create Account");
System.out.println("2. Display Accounts");
System.out.println("3. Deposit/Withdraw");
System.out.println("4. Delete Account");
System.out.println("5. Exit Program");
System.out.println("-----------------------------------------------");
do{
menuOption = keyboard.nextInt();
}while(menuOption <1 || menuOption >5);
return menuOption;
}
public class Account {
private int accNum;
private String accName;
private String accAdd;
private String accOpDate;
private double accOpBalance;
Scanner getDetails = new Scanner(System.in);
public Account(int theAccNum, String theAccName, String theAccAdd, String theAccOpDate, double theAccOpBalance){
accNum = theAccNum;
accName = theAccName;
accAdd = theAccAdd;
accOpDate = theAccOpDate;
accOpBalance = theAccOpBalance;
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public String getAccName(){
return accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public String getAccAdd(){
return accAdd;
}
public void setAccOpDate(String accOpDate){
this.accOpDate = accOpDate;
}
public String getAccOpDate(){
return 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;
}
}

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

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

Why is my program repeating itself. Java Error

I am supposed to make the program give the number of pets and the percentage of how many that are below 5lbs, 5-10lbs, and over 10lbs. The program keeps repeating the statements and I don't know why. I've been working on this problem for the past couple of days and I still can't figure it out. At times it seems like I fixed it but then later on it happens again. Can anyone clarify why this is happening? I need help please.
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.lang.Object;
public class SetPetWeight
{
public static void main(String[] args) {
ArrayList<Pet> list = new ArrayList<Pet>();
String name;
String answer;
int age;
Double weight;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
if(age <= 0)
System.out.println("Error! Enter a real age");
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
if(weight <= 0)
System.out.println("Error! Enter a real weight");
do
{
System.out.println("Do you want to enter another pet? Y/N");
answer = keyboard.nextLine();
keyboard.nextLine();
} while (answer.equalsIgnoreCase("Y"));
} while (name.length() < 0 && age < 0 && weight < 0);
System.out.println("The weight is now sorted by weight!");
Collections.sort(list, Pet.SortByWeight);
for (Pet p2 : list)
p2.writeOutput();
int average1 = 0;
int average2 = 0;
int average3 = 0;
for (Pet p : list)
{
if(p.getWeight() >= 0 && p.getWeight() <= 5)
{
++average1;
}
else if(p.getWeight() >= 5 && p.getWeight() <= 10)
{
++average2;
}
else if(p.getWeight() > 10)
{
++average3;
}
System.out.println("The average of pets under 5 pounds:" + average1);
System.out.println("The average of pets between 5 and 10 pounds:" + average2);
System.out.println("The average of pets over 10 pounds:" + average3);
}
}
}
Pet Class that is used for the SetPetWeight class and is compiled correctly and is used for the array.
import java.util.*;
public class Pet {
private String name;
private Integer age; // in years
private double weight; // in pounds
public void writeOutput() {
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName) {
name = newName;
// age and weight are unchanged.
}
public void set(int newAge) {
if (newAge <= 0) {
System.out.println("Error: illegal age.");
System.exit(0);
} else
age = newAge;
// name and weight are unchanged.
}
public void set(double newWeight) {
if (newWeight <= 0) {
System.out.println("Error: illegal weight.");
System.exit(0);
} else
weight = newWeight;
// name and age are unchanged.
}
public Pet(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public static Comparator<Pet> SortByWeight = new Comparator<Pet>()
{
public int compare(Pet pet1, Pet pet2)
{
return (int)(pet1.getWeight() - pet2.getWeight());
}
};
}
Move keyboard.nextLine(); after weight = keyboard.nextDouble(); to consume the dangling newline character .
There are a few changes you may want to make.
1. Every time you retrieve user input for pet's name, age and weight. You may want to create an object of type pet to store this values and then add this to your ArrayList. Before you ask them if they wan to add another pet.
2. Remove the outer do while loop, and change the inter loop to include the "Enter a String for pet name: ".
3. Also check for validation for input.
do {
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
if(age <= 0)
System.out.println("Error! Enter a real age");
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
keyboard.nextLine();
if(weight <= 0)
System.out.println("Error! Enter a real weight");
System.out.println("Do you want to enter another pet? Y/N");
answer = keyboard.nextLine();
keyboard.nextLine();
} while (answer.equalsIgnoreCase("Y"));

Categories