The program works but you need to type in Upper case or Lower case depending on the word. As well, when you choose 2 or more standard/deluxe toppings, it displays only the last input of each one. Definitely waiting for help :D. Thank you!
public class Sundae {
private final double SALES_TAX = .08625;
private final double DELUXE_TOPPING = 1.25;
private String iceCreamFlavor;
private int numberOfScoops;
private double costForScoops;
private String standardToppingList;
private String freeSyrupChoice;
private String deluxeToppingList;
private double costOfDeluxeToppings;
private int counterD;
private double costOfSundae;
private double tax;
private double total;
public Sundae()
{
}
public String getIceCreamFlavor()
{
return iceCreamFlavor;
}
public int getNumberOfScoops()
{
return numberOfScoops;
}
public double getCostForScoops()
{
return costForScoops;
}
public String getStandardToppingList()
{
return standardToppingList;
}
public String getFreeSyrupChoice()
{
return freeSyrupChoice;
}
public String getDeluxeToppingList()
{
return deluxeToppingList;
}
public double getCostOfDeluxeToppings()
{
return costOfDeluxeToppings;
}
public int getCounterD()
{
return counterD;
}
public double getCostOfSundae()
{
return costOfSundae;
}
public void setIceCreamFlavor(String choice)
{
iceCreamFlavor = choice;
}
public void setNumberOfScoops(int numberScoops)
{
numberOfScoops = numberScoops;
}
public void setCostForScoops()
{
costForScoops = numberOfScoops + 1.79;
}
public void setCounterD(int numberD)
{
counterD = numberD;
}
public void setStandardToppingList(String standardTopping)
{
standardToppingList = standardTopping;
}
public void setFreeSyrupChoice(String syrup)
{
freeSyrupChoice = syrup;
}
public void setDeluxeToppingList(String deluxeTopping)
{
deluxeToppingList = deluxeTopping;
}
public void setDefault()
{
iceCreamFlavor = "Vanilla";
numberOfScoops = 2;
costForScoops = 1.79;
standardToppingList = "Whipped Cream, Hot Fudge, Multi-Colored Sprinkles, and a cherry.";
}
public void Print()
{
costForScoops = numberOfScoops * 1.79;
costOfDeluxeToppings = DELUXE_TOPPING * counterD;
costOfSundae = costForScoops + costOfDeluxeToppings;
tax = SALES_TAX * costOfSundae;
total = costOfSundae + tax;
System.out.println("Flavor: " + iceCreamFlavor + "\nNumber of scoops: " + numberOfScoops + "\nCost for scoops: " + costForScoops
+ "\nStandard toppings: " + standardToppingList + "\nSyrup:" + freeSyrupChoice + "\nDeluxe toppings: " + deluxeToppingList
+ "\nCost of deluxe toppings: " + costOfDeluxeToppings);
System.out.printf("Subtotal: $%.2f \nSale Tax: $%.2f \nTotal: $%.2f", costOfSundae, tax, total);
}
}
Driver Program
import java.util.Scanner;
public class SundaeDriver {
public static void main(String[]args) {
Sundae sundae = new Sundae();
int numberS;
int numberD;
Scanner input = new Scanner(System.in);
System.out.println("Which sundae flavor do you want? ");
sundae.setIceCreamFlavor(input.nextLine());
if ((sundae.getIceCreamFlavor().equalsIgnoreCase("Vanilla"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("French Vanilla"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Peanut Butter"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate Chip"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate Chip Cookie"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Cookie Dough"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Ice Cream Cake"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("American Dream"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Vanilla Chocolate Swirl"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Strawberry"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Mint Chocolate Chip"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Oreo Cookies and Cream")))
{
}
else
{
sundae.setIceCreamFlavor("Vanilla");
}
System.out.println("How many scoops do you want?");
sundae.setNumberOfScoops(input.nextInt());
if ((sundae.getNumberOfScoops() == 1)||
(sundae.getNumberOfScoops() == 2)||
(sundae.getNumberOfScoops() == 3)||
(sundae.getNumberOfScoops() == 4)||
(sundae.getNumberOfScoops() == 5)||
(sundae.getNumberOfScoops() == 6))
{
}
else
{
sundae.setNumberOfScoops(2);
}
System.out.println("How many free toppings do you want?(free)");
numberS = input.nextInt();
input.nextLine();
for (int i = 0; i < numberS;i++)
{
System.out.println((i + 1) + " free toppings do you want?");
sundae.setStandardToppingList(input.nextLine());
if ((sundae.getStandardToppingList().equals("Whipped cream"))||
(sundae.getStandardToppingList().equals("Syrup"))||
(sundae.getStandardToppingList().equals("Multi colored sprinkles"))||
(sundae.getStandardToppingList().equals("Cherry")))
{
sundae.getStandardToppingList();
}
else
{
sundae.setStandardToppingList("Whipped cream, hot fudge, multi colored sprinkles and cherry");
}
}
System.out.println("Which syrup do you want?");
sundae.setFreeSyrupChoice(input.nextLine());
if ((sundae.getFreeSyrupChoice().equals("Hot fudge"))||
(sundae.getFreeSyrupChoice().equals("Chocolate"))||
(sundae.getFreeSyrupChoice().equals("Caramel")))
{
}
else
{
sundae.setFreeSyrupChoice("");
}
System.out.println("How many deluxe toppings do you want?");
numberD = input.nextInt();
sundae.setCounterD(numberD);
sundae.getCounterD();
input.nextLine();
for(int j = 0; j < numberD; j++)
{
System.out.println((j + 1) + " deluxe toppings do you want?");
sundae.setDeluxeToppingList(input.nextLine());
if((sundae.getDeluxeToppingList().equals("M&Ms"))||
(sundae.getDeluxeToppingList().equals("Crushed oreos"))||
(sundae.getDeluxeToppingList().equals("Reeses")||
(sundae.getDeluxeToppingList().equals("Chocolate chips"))||
(sundae.getDeluxeToppingList().equals("KitKats"))||
(sundae.getDeluxeToppingList().equals("Gummy Bears"))||
(sundae.getDeluxeToppingList().equals("Cookie Dough Bits"))||
(sundae.getDeluxeToppingList().equals("Marshmallows"))||
(sundae.getDeluxeToppingList().equals("Peanuts"))||
(sundae.getDeluxeToppingList().equals("Walnuts"))))
{
sundae.getDeluxeToppingList();
}
else
{
sundae.setDeluxeToppingList("");
}
}
sundae.Print();
input.close();
}
}
This looks like a perfect time to use enum(s). I'll provide an example for the first case. Ice cream flavors.
public enum IceCreamFlavors {
VANILLA, FRENCH_VANILLA, PEANUT_BUTTER, CHOCOLATE, CHOCOLATE_CHIP,
CHOCOLATE_CHIP_COOKIE, COOKIE_DOUGH, ICE_CREAM_CAKE, AMERICAN_DREAM,
VANILLA_CHOCOLATE_SWIRL, STRAWBERRY, MINT_CHOCOLATE_CHIP, OREOS_COOKIES_AND_CREAM;
public static IceCreamFlavors fromName(String name) {
for (IceCreamFlavors f : values()) {
if (f.name().replace('_', ' ').equalsIgnoreCase(name)) {
return f;
}
}
return IceCreamFlavors.VANILLA;
}
}
Then you can call it like
System.out.println("Which ice cream flavor do you want? ");
IceCreamFlavors flavor = IceCreamFlavors.fromName(input.nextLine());
And that way your logic for validation of the flavor it kept with-in the enum.
use:
private List<String> standardToppingList;
private List<String> deluxToppingList;
with Constructor containing:
standardToppingList = new Arraylist<>();
deluxToppingList = new Arraylist<>();
to add to the list, use:
standardToppingList.add(standardTopping);
deluxToppingList.add(deluxTopping);
and Display Using:
for(String s : deluxToppingList) {
System.out.println(s);
}
for(String s : standardToppingList) {
System.out.println(s);
}
Related
I am trying to code a text based Adventure Game, but the random enemy selection does not work. Always the "Assassin" gets chosen, but I can't figure out why.
package defaultdfs;
import java.util.Random;
import java.util.Scanner;
public class main {
// System Objects
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
//OBJ
static Entity s = new Entity("Skeleton", 200, 5, 2, 200);
static Entity z = new Entity("Zombie", 150, 2, 1, 150);
static Entity w = new Entity("Warrior", 175, 3, 1, 175);
static Entity a = new Entity("Assasin", 75, 1, 1, 75);
// Game Variables
static Entity[] enemies = {w, z, s, a};
static int maxEnemyHealth = 75;
static int enemyAttackDam = 25;
// Player Variables
static int health = 100;
static int attackDamage = 50;
static int numHealthPot = 3;
static int healthPotHealAmount = 30;
static int healthPotDropChance = 50;
static int ShieldDropChance = 0;
static int enemyCounter = 0;
static int defense = 0;
static int enemyHealth = 0;
static int damageDealt = 0;
static int damageTaken = 0;
//Items
static boolean sword = false;
static int swordDropChance = 0;
static boolean running = true;
static Entity enemy;
public static void main(String[] args) {
welcome();
GAME: while (running) {
System.out.println("-------------------------------------------------");
int ra = rand.nextInt(enemies.length); //RANDOM ENEMY SELECTION in two steps
enemy = enemies[ra];
// enemy = enemies[rand.nextInt(enemies.length)]; //in one step
System.out.println(ra);
System.out.println("\t# " + enemy.name + " appeared! #\n");
while (enemy.enemyHealth > 0) {
monitoring(enemy, Entity.enemyHealth);
String input = in.nextLine();
if (input.equals("1")) {
damageDealt = rand.nextInt(attackDamage);
damageTaken = rand.nextInt(enemyAttackDam);
enemy.enemyHealth -= damageDealt;
health -= damageTaken;
// Iteminfluence
health += defense;
System.out.println("\t> You strike the " + enemy.name + " for " + damageDealt + " damage.");
System.out.println("\t> You recive " + damageTaken + " in retaliation!");
if (health < 1) {
dead();
break;
}
} else if (input.equals("2")) {
healingProcess(enemy);
}
else if (input.equals("3")) {
runOption(enemy);
continue GAME;
}
else {
System.out.println("\tInvalid command!");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle!");
break;
}
defmsg(enemy);
enemyC();
healpot(enemy);
defense(enemy);
sword(enemy);
options();
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command!");
input = in.nextLine();
}
if (input.equals(input.equals("1"))) {
System.out.println("You continue on ypur adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventure!");
break;
}
}
thx();
}
private static void sword(Entity enemy) {
if (rand.nextInt(100) < swordDropChance) {
attackDamage += 5;
System.out.println(" # The " + enemy.name + " dropped a piece of armor! # ");
System.out.println(" # You attack now with +5! # ");
}
}
private static void defmsg(Entity enemy) {
System.out.println("-------------------------------------------------");
System.out.println(" # " + enemy.name + " was defeated! # ");
System.out.println(" # You have " + health + "HP left. # ");
enemy.enemyHealth = enemy.inHealth;
}
private static void options() {
System.out.println("-------------------------------------------------");
System.out.println("What would you like to do now? ");
System.out.println("1. Continue fighting");
System.out.println("2. Exit dungeon");
}
private static void thx() {
System.out.println("#######################");
System.out.println("# THANKS FOR PLAYING! #");
System.out.println("#######################");
}
private static void welcome() {
System.out.println("Welcome to the Dungeon!");
}
private static void attack(int enemyHealth, int damageDealt, int damageTaken) {
enemy.enemyHealth -= damageDealt;
health -= damageTaken;
// Iteminfluence
health += defense;
}
private static void dead() {
System.out.println("\t> You have taken too much damage, you are too weak to go on!");
}
private static void monitoring(Entity enemy, int enemyHealth) {
System.out.println("\tYour HP: " + health);
System.out.println("\t" + enemy.name + "'s HP: " + enemy.enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink health potion");
System.out.println("\t3. Run!");
}
private static void runOption(Entity enemy) {
System.out.println("\tYou run away from the " + enemy.name + "!");
}
private static void healingProcess(Entity enemy) {
if (numHealthPot > 0) {
int prevHealth = health;
health += healthPotHealAmount;
if (health == 100) {
System.out.println("You can not heal yourself!");
} else if (health > 100) {
health = 100;
numHealthPot--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotHealAmount + " . "
+ "\n\t> You now have " + health + " HP." + "\n\t> You have " + numHealthPot
+ " health potions left.\n");
} else {
numHealthPot--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotHealAmount + " . "
+ "\n\t> You now have " + health + " HP." + "\n\t> You have " + numHealthPot
+ " health potions left.\n");
}
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!");
}
}
private static void enemyC() {
enemyCounter++;
if (enemyCounter == 1) {
System.out.println(" # You killed one enemy! # ");
} else {
System.out.println(" # You killed " + enemyCounter + " enemies! # ");
}
}
private static void healpot(Entity enemy) {
if (rand.nextInt(100) < healthPotDropChance) {
numHealthPot++;
System.out.println(" # The " + enemy.name + " dropped a health potion! # ");
System.out.println(" # You now have " + numHealthPot + " heaalth potion(s). # ");
}
}
public static void defense(Entity enemy) {
if (rand.nextInt(100) < ShieldDropChance) {
defense += 5;
System.out.println(" # The " + enemy.name + " dropped a piece of armor! # ");
System.out.println(" # You now have " + defense + " defensepoints! # ");
}
}
}
I Tried to split the part up and print out the number it choose. And the random selection works but its always the same enemy which gets chosen.
public class Entity {
static String name;
static int enemyHealth = 100;
static int ShieldDropChance = 0;
static int swordDropChance = 0;
static int inHealth = 0;
public static int getSwordDropChance() {
return swordDropChance;
}
public static void setSwordDropChance(int swordDropChance) {
Entity.swordDropChance = swordDropChance;
}
public static int getShieldDropChance() {
return ShieldDropChance;
}
public static void setShieldDropChance(int shieldDropChance) {
ShieldDropChance = shieldDropChance;
}
public static String getName() {
return name;
}
public static void setName(String name) {
Entity.name = name;
}
public static int getEnemyHealth() {
return enemyHealth;
}
public static void setEnemyHealth(int enemyHealth) {
Entity.enemyHealth = enemyHealth;
}
public Entity (String name, int enemyHealth, int ShieldDropChance, int swordDropChance, int inHealth) {
this.name = name;
this.enemyHealth = enemyHealth;
this.ShieldDropChance = ShieldDropChance;
this.swordDropChance = swordDropChance;
this.inHealth = inHealth;
}
}
What Anon said. Change your entity class to this, and you shouldn't even need to touch the rest of your code.
Remember that static means it's one value associated with the class itself and not any particular instance. But for some reason, Java lets you reference static values via an instance (like you did), which does nothing except trick you into thinking it's not static. I really don't know why that's a thing.
public class Entity {
String name;
int enemyHealth = 100;
int shieldDropChance = 0;
int swordDropChance = 0;
int inHealth = 0;
public int getSwordDropChance() {
return swordDropChance;
}
public void setSwordDropChance(int swordDropChance) {
this.swordDropChance = swordDropChance;
}
public int getShieldDropChance() {
return shieldDropChance;
}
public void setShieldDropChance(int shieldDropChance) {
this.shieldDropChance = shieldDropChance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnemyHealth() {
return enemyHealth;
}
public void setEnemyHealth(int enemyHealth) {
this.enemyHealth = enemyHealth;
}
public Entity (String name, int enemyHealth, int ShieldDropChance, int swordDropChance, int inHealth) {
this.name = name;
this.enemyHealth = enemyHealth;
this.ShieldDropChance = ShieldDropChance;
this.swordDropChance = swordDropChance;
this.inHealth = inHealth;
}
}
I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class
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();
}
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?
I have a very simple solution but I have not yet learned how to do it and cannot figure out how to solve the problem.
I have an Interface class:
public interface Analyzable {
double getAverage();
GradedActivity getHighest();
GradedActivity getLowest();
}
This was given to me by my professor. I changed his code from the two GradedActivity to doubles and had no problem returning them in this code. However I am having trouble returning them as GradedActivity's
public GradedActivity getHighest() {
double highest = grades[0].getScore();
for(int i = )......
//Code works and returns correct number (tested)
return highest;
this code gives me this error
"Double cannot be converted to GradedActivity"
this is my GradedActivity code
public class GradedActivity {
private double score;
public GradedActivity() {
}
public void setScore(double s) {
score = s;
}
public double getScore() {
return score;
}
public char getGrade() {
char letterGrade;
if(score >= 90)
letterGrade = 'A';
else if(score >= 80)
letterGrade = 'B';
else if(score >= 70)
letterGrade = 'C';
else if(score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}
this is the CourseGrades code
enter code here
public class CourseGrades extends GradedActivity implements Analyzable
{
private GradedActivity[] grades = new GradedActivity[4];
public CourseGrades()
{
}
public void setLab(GradedActivity lab)
{
grades[0] = lab;
}
public void setPassFailExam(PassFailExam passFailExam)
{
grades[1] = passFailExam;
}
public void setEssay(GradedActivity essay)
{
grades[2] = essay;
}
public void setFinalExam(FinalExam finalExam)
{
grades[3] = finalExam;
}
public String toString() {
String str;
str = "Lab Score: " + grades[0].getScore() +
"\t\t\tGrade: " + grades[0].getGrade() +
"\nP/F Exam Score: " + grades[1].getScore() +
"\t\tGrade: " + grades[1].getGrade() +
"\nEssay Score: " + grades[2].getScore() +
"\t\tGrade: " + grades[2].getGrade() +
"\nFinal Exam Score: " + grades[3].getScore() +
"\t\tGrade: " + grades[3].getGrade();
return str;
}
public double getAverage()
{
double sum = 0;
for(int i = 0; i < 4; i++) {
sum += grades[i].getScore();
}
double ave = sum/4;
return ave;
}
public GradedActivity getHighest() {
double highest = grades[0].getScore();
for(int i = 1; i < 4; i++) {
if(grades[i].getScore() > highest)
highest = grades[i].getScore();
}
return highest;
}
public GradedActivity getLowest() {
double lowest = grades[0].getScore();
for(int i = 1; i < 4; i++) {
if(grades[i].getScore() < lowest)
lowest = grades[i].getScore();
}
return setScore(lowest);
}
}
this is the interface
public class CourseGrades extends GradedActivity implements Analyzable
{
private GradedActivity[] grades = new GradedActivity[4];
public CourseGrades()
{
}
public void setLab(GradedActivity lab)
{
grades[0] = lab;
}
public void setPassFailExam(PassFailExam passFailExam)
{
grades[1] = passFailExam;
}
public void setEssay(GradedActivity essay)
{
grades[2] = essay;
}
public void setFinalExam(FinalExam finalExam)
{
grades[3] = finalExam;
}
public String toString() {
String str;
str = "Lab Score: " + grades[0].getScore() +
"\t\t\tGrade: " + grades[0].getGrade() +
"\nP/F Exam Score: " + grades[1].getScore() +
"\t\tGrade: " + grades[1].getGrade() +
"\nEssay Score: " + grades[2].getScore() +
"\t\tGrade: " + grades[2].getGrade() +
"\nFinal Exam Score: " + grades[3].getScore() +
"\t\tGrade: " + grades[3].getGrade();
return str;
}
public double getAverage()
{
double sum = 0;
for(int i = 0; i < 4; i++) {
sum += grades[i].getScore();
}
double ave = sum/4;
return ave;
}
public GradedActivity getHighest() {
double highest = grades[0].getScore();
for(int i = 1; i < 4; i++) {
if(grades[i].getScore() > highest)
highest = grades[i].getScore();
}
return highest;
}
public GradedActivity getLowest() {
double lowest = grades[0].getScore();
for(int i = 1; i < 4; i++) {
if(grades[i].getScore() < lowest)
lowest = grades[i].getScore();
}
return setScore(lowest);
}
}
As a double can not be cast to a GradedActivity you need to create one first, set the value (I would create a constructor) and then return it.
try
GradedActivity highGA = new GradedActivity();
highGA.setScore (highest);
return highGA;
You need to take the value and wrap in a GradedActivity instance and return it, for example...
public GradedActivity getHighest() {
double highest = grades[0].getScore();
for(int i = )......
//Code works and returns correct number (tested)
GradedActivity ga = new GradedActivity();
ga.setScore(highest);
return ga;
Java won't convert from double to GradedActivity automatically you must create an new instance of GradedActivity and set its value.
GradedActivity ga = new GradedActivity(); // create instance
ga.setScore(value); // set value
return ga; // return GradedActivity instead of double