Why is my program repeating itself. Java Error - java

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

Related

Scanner cant read/incorrectly reading my input

I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}

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.

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

Creating a Bank program [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am almost done with an assignment. I am creating a Bank program, and I have almost everything done. The part that I am stuck on is the transactions part. I have to create a function public String getTransactionInfo(int n) which returns the last n transactions of a bank account. I cannot seem to figure this part out. i have a variable private int numOfTransactions and I tried incorporating that into the function, but it didn't work. this is what I tried.
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
that did not work. cannot figure out how to return this is a string. any ideas?
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print short account information");
System.out.println("5) Print the detailed account information including last transactions");
System.out.println("6) Quit");
System.out.println();
System.out.print("Enter choice [1-6]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1: System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
//case 5: ... break;
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts; // the number of bank accounts at this bank
// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer number and the balance of the bank account whose
// account number is given, together with last n transactions on that account. If the account is not
// available at the bank, it should print a message.
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(accounts[i].getTransactionInfo(n));
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public String getTransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
transactions = new double[100];
transactions[0] = balance;
numOfTransactions = 1;
}
public int getAccountNum(){
return accountNum;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
numOfTransactions++;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
numOfTransactions++;
}
}
}
}//end of class
}
I think the correct solution to your problem will be something like this:
public String gettransactionInfo(int n)
{
//Traverse the "transactions" array in *reverse* order
//In For loop start with transactions.length, and decrement by 1 "n" times
// Append the transaction amount to a String
// Return the string.
}
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
Hehe! What are you exactly trying to do here? :) ... You messed up the rvalue and lvalue, but that's not related to the answer.
The key is to have a String Array in the class. Every time a transaction happens append the transaction details to the array..... Then gettransactionInfo should print the last n details in the string...
e.g.
transInfo[0] = "A deposited 30K"
transInfo[1] = "B withdrew 20K"
transInfo[2] = "C deposited 5k"
Last 1 transaction displays the last entry in the string "C deposited 5k"
If you want to return the number of transactions as a String, as opposed to the integer (which you have it stored as), then you want to convert the integer to a String.
In Java, you would do so via:
Integer.toString(numOfTransactions)
Side note: Out of curiosity, in your program, why are you doing this?
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
That is inefficient and wrong since you are setting the numberOfTransactions to the n value. That functionality, by convention is put in a setter method, as opposed to a getter method - which is what your implementation is supposed to do.
Ideally, it should be:
public String gettransactionInfo()
{
return Integer.toString(numOfTransactions);
}
EDIT:
As per the comments, the correct thing to do would be to return an index from the transactions array, corresponding to index n.
Where, in this case the transactions array should be a String array.
EDIT 2:
In the case where you use a separate string array, you would update it (depending on the transaction) as follows:
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print short account information");
System.out.println("5) Print the detailed account information including last transactions");
System.out.println("6) Quit");
System.out.println();
System.out.print("Enter choice [1-6]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1: System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
case 5: System.out.println("Enter a account number");
anum = s.nextInt();
myBank.printTransactionInfo(anum);
break;
default: System.out.println("Invalid option. Please try again.");
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts; // the number of bank accounts at this bank
//Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
public void printTransactionInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println("Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer number and the balance of the bank account whose
// account number is given, together with last n transactions on that account. If the account is not
// available at the bank, it should print a message.
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(accounts[i].getTransactionInfo(n));
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private String[] transactionsSummary;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public String getTransactionInfo(int n)
{
String transaction = transactionsSummary[n];
if (transaction == null) {
return "No transaction exists with that number.";
}
else {
return transaction;
}
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
transactions = new double[100];
transactionsSummary = new String[100];
transactions[0] = balance;
transactionsSummary[0] = "A balance of : $" + Double.toString(balance) + " was deposited.";
numOfTransactions = 1;
}
public int getAccountNum(){
return accountNum;
}
public int getNumberOfTransactions() {
return numOfTransactions;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was deposited.";
numOfTransactions++;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was withdrawn.";
numOfTransactions++;
}
}
}
}//end of class
}
To convert an integer to a String:
String out = Integer.toString(n);
You description of case 5 is
Print the detailed account information including last transactions
Just returning the number of transactions as a string is not going to achieve that.
You need to store every transaction as it happens in the transactions array in your BankAccount class and then get the last n values in that array in the gettransactionInfo() function.
EDIT:
And btw, you have forgotten to call the openNewAccount() function
Convert primitive int to its wrapper class and call its toString() method
public String gettransactionInfo(int n) {
return new Integer(n).toString();
}

how to find two's best answers

I am trying to find two's greatest numbers that are entered from the console.
I found the first one, but the solution for the second one is not working. The program is compiling and running. Here is the code.
import java.util.Scanner;
public class FindingSecondHighestScore_4_09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double max = 1;
double score2 = 0;
String firstName = "";
String secondName = null;
System.out.println("Enter number of students: ");
int x = input.nextInt();
while(x > 0)
{
System.out.println("Enter Sudent's name");
String name = input.next();
System.out.println("Enter Student's score");
double score = input.nextDouble();
//find max
if(score > max)
{
max = score;
firstName = name;
}
//find second max
if(max < score2 || score < score2)
{
max = score2;
score = score2;
}
else if(max > score2 && score2 < score)
{
score2 = score;
secondName = name;
}
x--;
}
System.out.println("The student: " + firstName + " has the greatest score: " + max);
System.out.println("Second studemt " + secondName + " with second results: " + score2);
}
}
Here is a bit more elaborate implementation (my waking up excercise of today):
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TopScores {
private static final int TOP_SELECTION_SIZE = 2;
public static class Student {
private final String name;
private double score;
public Student(String name) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Name cannot be empty");
}
this.name = name;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public void setScore(String score) {
try {
this.score = Double.parseDouble(score);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal score: " + score);
}
}
#Override
public String toString() {
return String.format("%s with score %s", name, score);
}
}
public static void main(String[] args) {
List<Student> students = new ArrayList<TopScores.Student>();
System.out.println("Please enter students. Press <RETURN> to stop.");
Scanner input = new Scanner(System.in);
boolean enteringData = true;
while (enteringData) {
try {
System.out.print("Enter student's name: ");
Student student = new Student(input.nextLine());
System.out.print("Enter student's score: ");
student.setScore(input.nextLine());
for (int i = 0; i < students.size(); i++) {
if (student.getScore() > students.get(i).getScore()) {
students.add(i, student);
break;
}
}
if (students.size() == 0) {
students.add(student);
}
} catch (IllegalArgumentException e) {
enteringData = false;
}
}
int studentsToDisplay = Math.min(TOP_SELECTION_SIZE, students.size());
if (studentsToDisplay > 0) {
System.out.println("Top students:");
for (int i = 0; i < studentsToDisplay; i++) {
System.out.println("* " + students.get(i));
}
} else {
System.out.println("No students to display");
}
}
}
I created a separate class Student which holds name and score, validates the input and creates the display format for one student.
To determine the top scores I keep all the entered students sorted in a list by adding each new student in the correct position.
The user doesn't have to enter the number of students beforehand but can terminate data entry by entering an empty line (or an invalid score).
After data entry is finished the desired number of top scoring students is printed.
This approach is more flexible; printing the top 3 or top 10 students is a matter of changing the value of TOP_SELECTION_SIZE.
Most important takeaway: try to think in classes (in this case Student) where possible and delegate sensible responsibilities to each class.
Since this looks like homework, I will just give you a few hints:
When you find a new max, what should happen to score2?
Should you look for a new score2 even if you found a new max?
If we want to address the if structures, consider rearranging to something like this:
if (/* new score beats second score, but not first */) {
// replace second score
} else if (/* new score beats both first and second */) {
// move first score down to second
// assign a new first score
}
Let your thought process to correspond closely to the code, which will clarify what each block should do, thus localizing any logic errors.
I think when score is greater than max then have to shift max into second score and set max with new score....
And
When the score is between max and score2 then have to update score2 only with new score
//find max
if(score > max)
{
score2 = max;
max = score;
secondName = firstName;
firstName = name;
}
//find second max
if(score < max && score > score2)
{
score2 = score;
secondName = name;
}

Categories