How to fix "looping and candidate voting" error in Java - java

I'm making a voting system, and want the voting system to loop until the user enters 0 and the candidate that wins will be outputted
two classes
package javaexamcode;
import java.util.Scanner;
public class JavaExamCode {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Nominee mickey = new Nominee("Mickey Mouse");
Nominee donald = new Nominee("Donald Duck");
Nominee minnie = new Nominee("Minnie Mouse");
Nominee goofy = new Nominee("Goofy");
Scanner in = new Scanner(System.in);
while (true) {
System.out.println();
System.out.println("The presidential nominees are:");
System.out.println("1. Mickey Mouse");
System.out.println("2. Donald Duck");
System.out.println("3. Minnie Mouse");
System.out.println("4. Goofy");
System.out.print("What is your vote? ");
try{
int vote=in.nextInt();
if (vote==0){
break;
}else if (vote == 1){
mickey.increaseVote();
}else if (vote == 2){
donald.increaseVote();
}else if (vote == 3){
minnie.increaseVote();
}else if (vote ==4){
goofy.increaseVote();
}
else {
System.out.println("invalid");
}
break;
} catch (Exception e){
System.out.println("Invalid entry, try again");
continue;
}
}
Nominee[] candidates = new Nominee[]{mickey,donald,minnie,goofy};
Nominee president = winner(candidates);
System.out.println("The winner is " + president.toString() + " with " + president.totalVotes() + " votes.");
}
public static Nominee winner(Nominee[] all){
Nominee most = all[0];
for (int i = 1; i < all.length - 1; i++){
if (all[i].totalVotes() > most.totalVotes()){
most = all[i];
}else if (all[i].totalVotes() == most.totalVotes()){
String newName = all[i].toString() + " " + most.toString();
most = new Nominee(newName, (all[i].totalVotes() + most.totalVotes()));
}
}
return most;
}
}
package javaexamcode;
public class Nominee{
private String name;
private int votes;
public Nominee(String name){
this.name = name;
}
public Nominee (String name, int votes){
this.name = name;
this.votes = votes;
}
public void increaseVote(){
votes++;
}
public String toString(){
return name;
}
public int totalVotes(){
return votes;
}
}
There is also an error when you type 4 then it outputs that the winner is mickey and minnie with 0 votes.
Help would be greatly appreciated
I have searched online but could not find much

In your method:
public static Nominee winner(Nominee[] all){
Nominee most = all[0];
for (int i = 1; i < all.length - 1; i++){
if (all[i].totalVotes() > most.totalVotes()){
most = all[i];
}else if (all[i].totalVotes() == most.totalVotes()){
String newName = all[i].toString() + " " + most.toString();
most = new Nominee(newName, (all[i].totalVotes() + most.totalVotes()));
}
}
return most;
}
your for loop is ignoring the last candidate (#4 in this case)
Instead of the looping condition i < all.length - 1 you need to loop to i < all.length instead.

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

No more than a number of the same string name in the same array?

The problem I have encountered is as follows: I have created 10 row outputs representing docking spaces for ships.
But the dock can accommodate two sizes of ship; cargo and container. The rows are made up of 5 small and 5 medium. A cargo ship (small) can berth in any available space. A container ship (medium) can berth in the medium space, but not in small spaces.
So if I enter shipName and Container for example it searches the array making sure there is less than 5 Container's so it can dock i.e. save in the array. Can you help?
Here's my dock method:
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printArray();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
int dockCapacity = 0;
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//search for 5 small 3 med 2 large
// if what they entered equals shipSize more than 5 than cannot dock.
for(int i = 1; i < dock1.length; i++) {
if (dock1[i].getShipSize().equals(size)) {
System.out.print(dock1[i].getShipSize());
}
else {
System.out.println("Couldn't dock");
}
}
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null){
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Ship has been docked");
}
else{
System.out.println("Couldn't dock");
}
// printArray();
}
public static void undock(){
System.out.println("Status of ships: ");
printArray();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for(int i = 1; i < dock1.length; i++){
if(dock1[i] != null && dock1[i].getShipName().equals(name)){
dock1[i] = null;
System.out.println("Ship removed");
break;
}
else{
System.out.println("Ship not docked here");
}
}
}
public static void printArray() {
System.out.println("Docks:");
for(int i = 0; i < dock1.length; i++)
{
if(dock1[i] == null)
{
System.out.println("Dock " + i + " is empty");
}
else
{
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
}
Ship class
public class Ship {
private String shipName;
private String shipSize;
public String getShipName() {
return shipName;
}
public void setShipName(String shipName) {
this.shipName = shipName;
}
public String getShipSize() {
return shipSize;
}
public void setShipSize(String shipSize) {
this.shipSize = shipSize;
}
public Ship(String shipName, String shipSize) {
this.shipName = shipName;
this.shipSize = shipSize;
}
}
I would recommend you to change the Ship class like this. It adds a ShipSize enum and makes it much easier to parse the ship size from string and compare ship sizes. Also, I added a isCargo and isContainer method.
import java.util.Arrays;
public class Ship {
private String shipName;
private ShipSize shipSize;
public Ship(String shipName, ShipSize shipSize) {
this.shipName = shipName;
this.shipSize = shipSize;
}
public String getShipName() {
return shipName;
}
public void setShipName(String shipName) {
this.shipName = shipName;
}
public ShipSize getShipSize() {
return shipSize;
}
public void setShipSize(ShipSize shipSize) {
this.shipSize = shipSize;
}
public boolean isCargo() {
return shipSize == ShipSize.CARGO;
}
public boolean isContainer() {
return shipSize == ShipSize.CONTAINER;
}
public enum ShipSize {
CARGO,
CONTAINER;
public static ShipSize of(String size) {
return Arrays.stream(ShipSize.values()).filter(enumSize -> enumSize.name().equalsIgnoreCase(size)).findAny().orElse(null);
}
}
}
I also modified your main class so it does what you want. I added some parsing and checks for the numbers, added an initialize method for the docks.
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Dock[] dock1 = new Dock[10];
public static void main(String[] args) {
initializeDock();
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printArray();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
private static void initializeDock() {
for (int i = 0; i < 5; i++) {
dock1[i] = new Dock(Ship.ShipSize.CARGO);
}
for (int i = 5; i < 10; i++) {
dock1[i] = new Dock(Ship.ShipSize.CONTAINER);
}
}
public static void dock() {
int dockCapacity = 0;
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
Ship.ShipSize size = null;
while(size == null) {
System.out.println("Enter ship's size: ");
String stringSize = scan.nextLine();
size = Ship.ShipSize.of(stringSize);
if (size == null) {
System.out.println("Could not read ship size. Only cargo and container are allowed.");
}
}
// check that ship fits into any dock
if (size == Ship.ShipSize.CONTAINER) {
long numberOfContainerShips = Arrays.stream(dock1).map(Dock::getDockedShip).filter(Objects::nonNull).filter(Ship::isContainer).count();
if (numberOfContainerShips >= 5) {
System.out.println("No place for a ship that large. Aborting.");
return;
}
}
System.out.println("Enter the ships dock:");
Integer dockNumber = null;
while(dockNumber == null) {
dockNumber = scan.nextInt();
if (dockNumber < 0 || dockNumber > dock1.length - 1) {
System.out.println("Illegal dock number. Only numbers between 0 and " + dock1.length + " are allowed.");
dockNumber = null;
}
}
Dock dock = dock1[dockNumber];
if (dock.getDockedShip() != null) {
System.out.println("Dock reserved - couldn't dock");
return;
}
if (dock.getSupportedSize() == Ship.ShipSize.CARGO && size == Ship.ShipSize.CONTAINER) {
System.out.println("Dock too small - couldn't dock");
return;
}
dock.setDockedShip(new Ship(name, size));
}
public static void undock(){
System.out.println("Status of ships: ");
printArray();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for(int i = 1; i < dock1.length; i++){
if(dock1[i].getDockedShip() != null && dock1[i].getDockedShip().getShipName().equals(name)){
dock1[i] = null;
System.out.println("Ship removed");
break;
}
else{
System.out.println("Ship not docked here");
}
}
}
public static void printArray() {
System.out.println("Docks:");
for(int i = 0; i < dock1.length; i++)
{
if(dock1[i].getDockedShip() == null)
{
System.out.println("Dock " + i + " is empty. Size: " + dock1[i].getSupportedSize().name().toLowerCase());
}
else
{
System.out.println("Dock " + i + ": " + dock1[i].getDockedShip().getShipName() + " " + dock1[i].getDockedShip().getShipSize().name().toLowerCase());
}
}
}
}
I also added a Dock class. It works fine.
public class Dock {
private Ship.ShipSize supportedSize;
private Ship dockedShip = null;
public Dock(Ship.ShipSize supportedSize) {
this.supportedSize = supportedSize;
}
public Ship.ShipSize getSupportedSize() {
return supportedSize;
}
public void setSupportedSize(Ship.ShipSize supportedSize) {
this.supportedSize = supportedSize;
}
public Ship getDockedShip() {
return dockedShip;
}
public void setDockedShip(Ship dockedShip) {
this.dockedShip = dockedShip;
}
}

In my shop project, my method "checkout" runs several times before stopping when it should only run once when called upon form direct

import java.util.*;
public class Shop {
protected String name;
protected double price;
protected int amount;
protected double discountAmt;
protected double discount;
protected boolean setupComp = false;
protected boolean buyComp = false;
public static void main(String[] args) {
Shop direct = new Shop();
direct.direct();
}
public void direct(){
println("This program supports 4 functions:");
println("\t*Setup Shop");
println("\t*Buy Items");
println("\t*List of items purchased");
println("\t*Checkout");
print("Please choose the function you want: ");
Scanner input = new Scanner(System.in);
int func = input.nextInt();
if (func == 1){
setup();
}
if (func == 2){
buy();
}
if (func == 3){
listItems();
}
1. Everything seems to run fine up to this point, then checkout repeatedly runs a couple of times.
2. I don't know if the problem is how I'm calling upon checkout() or if it is within checkout itself:
if (func == 4);{
checkout();
}
if (func >= 5){
println("Error: do not know " + func);
direct();
}
}
public Shop(){
name = "";
price = 0;
amount = 0;
}
public Shop[] product;
private static void println(String string) {
System.out.println(string);
}
private static void print(String string) {
System.out.print(string);
}
public void setup(){
print("Please enter the number of items: ");
Scanner input = new Scanner(System.in);
int max = input.nextInt();
product = new Shop[max];
for (int i = 0; i < max; i++){
product[i] = new Shop();
print("Enter name of product " + i + ": ");
product[i].setName(name = input.next());
print("Enter the price of the product: ");
product[i].setPrice(price = input.nextDouble());
}
print("Please enter the amount to qualify for discount: ");
this.discountAmt = input.nextDouble();
print("Please enter the discount rate(0.1 for 10%): ");
this.discount = input.nextDouble();
setupComp = true;
direct();
}
public void buy(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true){
Scanner input = new Scanner(System.in);
for (int i = 0; i < product.length; i++){
print("Enter the amount of " + product[i].name + ": ");
product[i].setAmount(amount = input.nextInt());
buyComp = true;
}
direct();
}
}
public void listItems(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true && buyComp == false){
println("Try again: You have not bought anything");
direct();
}
for (int i = 0; i < product.length; i++){
if (product[i].amount == 0)
continue;
else println(product[i].amount + " count of " + product[i].name + " # " + product[i].price
+ " = " + (product[i].amount * product[i].price));
}
direct();
}
public void checkout(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true && buyComp == false){
println("Try again: You have not bought anything");
direct();
}
double subtotal = 0;
double total = 0;
double disc = 0;
for (int i = 0; i < product.length; i++){
subtotal += (product[i].amount * product[i].price);
}
if (subtotal >= discountAmt){
disc =(discount * subtotal);
total = subtotal - (disc);
}
3. These printline statements are what are running repeatedly. My method not these println statements are contained within a loop so I don't know what could be causing this issue.:
println("Thank you for coming!");
println("Sub Total: $" + subtotal);
println("-Discount: $" + (disc));
println("total\t: $" + total);
}
public void setName(String name){
this.name = name;
}
private void setPrice(double price) {
this.price = price;
}
private void setAmount(int amount) {
this.amount = amount;
}
}
Actually the if statement is an empty control flow. The checkout method is not getting called as intended by you. Please remove the first semicolon.
if (func == 4);{
checkout();
}

Java Constructor & Arrays

I am learning java. This is for a class that I take online. My assignment is finished.
I am trying to figure out the cause for the following.
The two main issues I have are:
1)It seems to be storing only one flower and ignoring the other inputs. How can I correct this?
2) Display flower (e.g Roses - 2):
Immediately after it displays the flowers and their count it will give me the following error message.
Flower Pack:
Daffodils - 1
Roses - 1
Exception in thread "main" java.lang.NullPointerException
at Assignment2.displayFlowers(Assignment2.java:203)
at Assignment2.<init>(Assignment2.java:44)
at Assignment2.main(Assignment2.java:9)
I believe it's origination from this statement
flowerName = searchingPack[i].getName();
Here is my code:
public class Flower {
private String name;
private String color;
private String thorns;
private String smell;
public Flower(){
}
public Flower(String flowerName, String flowerColor, String flowerThorns, String flowerSmell){
name = flowerName;
color = flowerColor;
thorns = flowerThorns;
smell = flowerSmell;
}
public String getName(){
return name;
}
public void setName(String flowerName){
name = flowerName;
}
public String getColor(){
return color;
}
public void setColor(String flowerColor){
color = flowerColor;
}
public String getThorns(){
return thorns;
}
public void setThorns(String flowerThorns){
thorns = flowerThorns;
}
public String getSmell(){
return smell;
}
public void setSmell(String flowerSmell){
smell = flowerSmell;
}
}
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args){
new Assignment2 ();
}
// This will act as our program switchboard
public Assignment2 (){
Scanner input = new Scanner(System.in);
Flower[] flowerPack = new Flower[25];
System.out.println("Welcome to my flower pack interface.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add an item to the pack.");
System.out.println("2: Remove an item from the pack.");
System.out.println("3: Search for a flower.");
System.out.println("4: Display the flowers in the pack.");
System.out.println("0: Exit the flower pack interfact.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower(flowerPack);
break;
case 2:
removeFlower(flowerPack);
break;
case 3:
searchFlowers(flowerPack);
break;
case 4:
displayFlowers(flowerPack);
break;
case 0:
System.out.println("Thank you for using the flower pack interface. See you again soon!");
System.exit(0);
}
}
}
//ADD FLOWERS
private void addFlower(Flower[] flowerPack) { //This is storing 1 flower but not anything else*********
Scanner add = new Scanner(System.in);
String name,color, thorns, smell;
System.out.println("\nEnter the name of the flower to add: ");
name = add.nextLine();
System.out.println("\nEnter the color of the flower: ");
color = add.nextLine();
System.out.println("\nAre there thorns present: YES or NO ");
thorns = add.nextLine();
System.out.println("\nDoes the flower smell: YES or NO ");
smell = add.nextLine();
boolean flowerInserted = false;
for(int i = 0; i < flowerPack.length; i++){
if(flowerPack[i] == null){
Flower newFlower = new Flower(name, color, thorns, smell);
flowerPack[i] = newFlower;
flowerInserted = true;
break;
}
}
if(flowerInserted){
System.out.println("Flower inserted.");
System.out.println();
}else{
System.out.println("\nFlower pack is full and could not add another flower.\n");
}
}
//REMOVE FLOWERS
private void removeFlower(Flower[] flowerPack) {
Scanner remove = new Scanner(System.in);
String removeName, removeColor;
for(int i = 0; i < flowerPack.length; i++){
System.out.println("\nEnter the name of the flower to remove: ");
removeName = remove.nextLine();
System.out.println("\nEnter the color of the flower: ");
removeColor = remove.nextLine();
if (flowerPack[i] != null)
if (flowerPack[i].getName().equalsIgnoreCase(removeName) && flowerPack[i].getColor().equalsIgnoreCase(removeColor)){
for(int j = i; j < flowerPack.length - 1; j++) {
flowerPack[j] = flowerPack[j + 1];
}
flowerPack[flowerPack.length - 1] = null;
System.out.println("\nFlower removed.\n");
break;
}
else{
System.out.println("\nThat flower was not found.\n");
}
}
}
//SEARCH FOR FLOWERS
private void searchFlowers(Flower[] flowerPack) {
Scanner flowerSearch = new Scanner(System.in);
String name, color, thorns, smell;
int options;
System.out.println("1: Seach by name.");
System.out.println("2: Seach by color.");
System.out.println("3: Seach for flowers with thorns.");
System.out.println("4: Seach for flowers that smell.");
options = flowerSearch.nextInt();
flowerSearch.nextLine();
boolean found = false;
for(int i = 0; i < flowerPack.length; i++){
if(options == 1){
System.out.println("\nEnter the name of the flower: ");
name = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getName().equalsIgnoreCase(name)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(options == 2){
System.out.println("\nEnter the color of the flower: ");
color = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getColor().equalsIgnoreCase(color)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(options == 3){
System.out.println("\nFlowers with thorns or no thorns: YES or NO ");
thorns = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getThorns().equalsIgnoreCase(thorns)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(options ==4){
System.out.println("\nFlower with aroma or no aroma: YES or NO ");
smell = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getSmell().equalsIgnoreCase(smell)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(!found){
System.out.println("\nSorry, no match found.");
}
}
}
//DISPLAY FLOWERS
private void displayFlowers(Flower[] flowerPack) {
System.out.println("Flower Pack: \n");
Flower[] searchingPack = new Flower[flowerPack.length];
for (int i = 0; i < searchingPack.length; i++) {
searchingPack[i] = flowerPack[i];
}
String flowerName = null;
int count = 0;
for(int i = 0; i < searchingPack.length; i++) {
i = 0;
flowerName = searchingPack[i].getName(); // this line is giving me an error!***********************************
if (searchingPack[i].getName() == null || searchingPack[i].getName().equals(null)) {
break;
}
for (int j = 0; j < flowerPack.length; j++) {
if (flowerPack[j] != null) {
if (flowerPack[j].getName().equalsIgnoreCase(flowerName)) {
count++;
}
}
}
for (int k = 0; k < count; k++) {
silentRemove(searchingPack, flowerName);
}
System.out.println(flowerName + " - " + count);
System.out.println();
count = 0;
}
}
private void silentRemove(Flower flowerPack[], String flowerName) {
for (int i = 0; i < flowerPack.length; i++) {
if (flowerPack[i] != null) {
if (flowerPack[i].getName().equalsIgnoreCase(flowerName)) {
for (int j = i; j < flowerPack.length - 1; j++) {
flowerPack[j] = flowerPack[j + 1];
}
flowerPack[flowerPack.length - 1] = null;
break;
}
}
}
}
}
Does it need to be an array? A List<Flower> is more appropriate here. What is happening is you're only adding 2 flowers, but looping over all 25 elements in the array, some of which are still null
The problem is with
flowerName = searchingPack[i].getName();
because searchingPack[i] might be null and then you're trying to reach an address that doesn't exists.
do something like this:
if(searchingPack[i]==null)
flowerName="";
else
flowerName = searchingPack[i].getName();
If you are planning on doing the same kinds of actions you might consider putting an "empty" flower at each index in the array so it won't throw an error.

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

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

Categories