show balance in simple atm in java - java

This code models a simple ATM machine that can deposit, withdraw, and show the 10 latest transactions in an array of 10 index values.
My problem is that I can't get the balance right after 10 deposits, the balance only seems to sum the values in my array, not including the transactions made before those ten. What am I doing wrong?
import java.util.Scanner;
public class cashier2 {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int amount = 0;
int choice = 0;
int[] transactions = new int[10];
int sum = 0;
int balance = 0;
while(choice != 4)
{
choice = menu();
switch(choice)
{
case 1:
System.out.print("deposit");
sum = keyboard.nextInt();
if(sum == 0)
{
System.out.print("wrong amount");
System.out.println();
System.out.println();
}
else
{
amount = (int) + sum;
makeTransactions(amount, transactions);
}
break;
case 2:
System.out.print("withdrawal ");
sum = keyboard.nextInt();
if(sum == 0)
{
System.out.print("wrong amount");
System.out.println();
System.out.println();
}
else
{
amount = (int) - sum;
makeTransactions(amount, transactions);
}
break;
case 3:
showTransactions(transactions, balance);
break;
case 4:
System.out.println("Exit");
break;
}
}
}
public static int menu()
{
Scanner keyboard = new Scanner(System.in);
int choice = 0;
System.out.println("Simple atm");
System.out.println();
System.out.println("1. deposit");
System.out.println("2. withdrawal");
System.out.println("3. balance");
System.out.println("4. exit");
System.out.println();
System.out.print("your choice: ");
choice = keyboard.nextInt();
return choice;
}
public static void showTransactions(int[] transactions, int balance)
{
System.out.println();
System.out.println("Tidigare transaktioner: ");
System.out.println();
for(int i = 0; i < transactions.length; i++)
{
if(transactions[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(transactions[i] + "\n");
balance = balance + transactions[i];
}
}
System.out.println();
System.out.println("Saldo: " + balance + " kr" + "\n");
System.out.println();
}
public static void makeTransactions(int amount, int[] transactions)
{
int position = findNr(transactions);
if (position == -1)
{
moveTrans(transactions);
position = findNr(transactions);
transactions[position] = amount;
}
else
{
transactions[position] = amount;
}
}
public static int findNr(int[] transactions)
{
int position = -1;
for(int i = 0; i < transactions.length; i++)
{
if (transactions[i] == 0)
{
position = i;
break;
}
}
return position;
}
//}
public static void moveTrans(int [] transactions)
{
for(int i = 0; i < transactions.length-1; i++)
{
transactions[i] = transactions[i + 1];
}
transactions[transactions.length-1] = 0;
}
}

Related

update a variable in a different class

How do I make amount() in class Casino.java store the total value and allow it to be returned to the class Roulette.java.
When I use:
int amount = Casino.amount();
It gives me several hundred lines of errors.
What I want done is to run the game number() and store the value into Casino.amount()
Please note in class Roulette.java there is a function called amountUpdate() which should update Casino.amount().
This is class Casino.java
package Casino;
import java.util.*;
public class Casino {
static String player = "";
static int playAmount = 0;
public static void main(String[] args) {
System.out.println("Welcome to Michael & Erics Casino!");
player();
ask();
start();
}
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
player = sc.nextLine();
}
return player;
}
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("How much would you like to play with? ");
playAmount = sc.nextInt();
if (playAmount < 1) {
System.out.println("Please enter a value that is more than $1");
playAmount = 0;
}
System.out.println("You are playing with: $" + playAmount + "\n");
}
public static int amount() {
int amount = playAmount;
if (Roulette.amountUpdate() >= 1) {
amount += Roulette.amountUpdate();
}
return amount;
/*if (Blackjack.amountUpdate() >= 1)
amount += Blackjack.amountUpdate();
return amount;*/
}
public static void start() {
System.out.println("Which table would you like to play at?");
System.out.println("1: Blackjack");
System.out.println("2: Roulette");
System.out.println("3: Check Balance");
System.out.println("4: Exit");
Scanner sc = new Scanner(System.in);
int table = sc.nextInt();
switch (table) {
case 1:
//blackjack.main(new String[]{});
break;
case 2:
Roulette.main(new String[]{});
break;
case 3:
System.out.println("You have : $" + playAmount);
start();
break;
case 4:
System.exit(0);
break;
}
}
}
This is class Roulette.java
package Casino;
import java.util.*;
import java.lang.*;
public class Roulette {
public static void main(String[] args) {
System.out.println("Welcome to the roulette table " + Casino.player());
placeBet();
amountUpdate();
//number();
}
public static int amountUpdate() {
int amount = 0;
if (number() > 0) {
amount += number();
}
if (br() > 0) {
amount += br();
}
if (oe() > 0) {
amount += oe();
}
if (third() > 0) {
amount += third();
}
return amount;
}
public static void placeBet() {
Scanner sc_Choice = new Scanner(System.in);
System.out.println("What would you like to bet on?");
System.out.println("1: Numbers");
System.out.println("2: Black or Red");
System.out.println("3: Odd or Even");
System.out.println("4: One Third");
System.out.println("5: Count Chips");
System.out.println("6: Restart");
int choice = sc_Choice.nextInt();
if (choice > 0 && choice < 7) {
switch (choice) {
case 1:
number();
break;
case 2:
br();
break;
case 3:
oe();
break;
case 4:
third();
break;
case 5:
System.out.println(Casino.amount());
break;
case 6:
Casino.main(new String[]{});
break;
}
} else {
System.out.println("You must choose between 1 and 6");
}
}
public static int number() {
Boolean betting = true;
//int amount = Casino.amount();
int amount = 5000;
int number;
int winnings;
String reply;
int betX;
int betAgain = 1;
Scanner sc_Number = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> bet = new ArrayList<Integer>();
while (betAgain == 1) {
System.out.println("What number would you like to place a bet on?");
int listCheck = sc_Number.nextInt();
if (listCheck >= 0 && listCheck <= 36) {
list.add(listCheck);
} else {
System.out.println("You must choose a number between 0 and 36");
}
System.out.println("How much do you want to bet?");
betX = sc_Number.nextInt();
if (betX > amount) {
System.out.println("You have insufficient funds to make that bet");
number();
} else if (betX < 1) {
System.out.println("You must bet more than 1$");
} else {
bet.add(betX);
amount = amount - betX;
}
System.out.println("Do you want to bet on more numbers?");
reply = sc_Number.next();
if (reply.matches("no|No|false|nope")) {
betAgain = betAgain - 1;
//No - Don't bet again
} else {
betAgain = 1;
//Yes - Bet again
}
int result = wheel();
System.out.println("Spinning! .... The number is: " + result);
for (int i = 0; i < bet.size(); i++) {
if (list.get(i) == result) {
winnings = bet.get(i) * 35;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
}
}
betAgain = betAgain - 1;
}
return amount;
}
public static int wheel() {
Random rnd = new Random();
int number = rnd.nextInt(37);
return number;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int br() {
Scanner sc_br = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Black or Red?");
String replyBR = sc_br.nextLine();
boolean black;
//****************
if (replyBR.matches("black|Black")) {
black = true;
} else {
black = false;
}
System.out.println("How much would you like to bet?");
int betBR = sc_br.nextInt();
if (betBR > amount) {
System.out.println("You have insufficient funds to make that bet");
br();
} else if (betBR < 1) {
System.out.println("You must bet more than 1$");
br();
} else {
amount = amount - betBR;
}
//*****************
boolean resultColour = colour();
if (resultColour == black) {
winnings = betBR * 2;
//PRINT OUT WHAT COLOUR!!!
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
}
System.out.println("Current Balance: " + amount);
return amount;
}
public static boolean colour() {
Random rnd = new Random();
boolean colour = rnd.nextBoolean();
return colour;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int oe() {
Scanner sc_oe = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Odd or Even?");
String replyOE = sc_oe.next();
System.out.println("How much would you like to bet?");
int betOE = sc_oe.nextInt();
if (betOE > amount) {
System.out.println("You have insufficient funds to make that bet");
oe();
}
amount = amount - betOE;
boolean resultOE = oddOrEven();
//PRINT OUT IF IT WAS ODD OR EVEN
if (resultOE == true) {
winnings = betOE * 2;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean oddOrEven() {
Random rnd = new Random();
boolean num = rnd.nextBoolean();
return num;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int third() {
Scanner sc_Third = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on 1st, 2nd or 3rd third?");
String replyT = sc_Third.next();
System.out.println("How much would you like to bet?");
int betT = sc_Third.nextInt();
if (betT > amount) {
System.out.println("You have insufficient funds to make that bet");
third();
}
amount = amount - betT;
boolean resultT = thirdResult();
//PRINT OUT WHAT NUMBER IT WAS AND IF IT WAS IN WHICH THIRD
if (resultT == true) {
winnings = betT * 3;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean thirdResult() {
Random rnd = new Random();
int num = rnd.nextInt(2);
if (num == 0) {
return true;
} else {
return false;
}
}
}
Looks like you're probably running into a StackOverflowException. When you call Casino.amount() inside of Roulette.number(), it then calls Roulette.amountUpdate(), which then calls Roulette.number(). Your methods are stuck in an infinite loop like this. You'll need to redesign your code such that these 3 functions are not all dependent on each other.
Your code is terse, so it's hard to help you fully solve the problem, but I believe you would benefit from splitting up your "amount" variable into separate entities. Keep things like bet amount, winnings, and such separate until you need to combine them.
Another issue you may run into is thatRoulette.amountUpdate() is called twice in Casino.amount(), but Roulette.amountUpdate() will not necessarily return the same thing both times. Consider storing the return value from the first call instead of calling it twice.

Why am I getting 1 as result after using "i" as my array index?

I've made a class named Car with methods that should resemble some functions of a real car. I'm trying to get the car's number of both the heaviest car and smallest car's engine.
As shown in my code below, you can see that I've done the validation using an index and then comparing that to "i". However, no matter what number I enter, I get "1" as result on both validations.
What could be wrong? I should be getting the number of the car instead of just "1".
Here is my code to get the heaviest car:
int weight = x[i].getweight();
if(weight > max) {
maxweight = weight;
maxIndex = i;
}
My Car class:
public class Car
{
private String color;
private int weight;
private int state;
private int fuel;
private int Maxspeed ;
private int engine;
public Car() {
this.color = "White";
this.weight = 1000;
this.state = 0;
this.fuel =0;
this.Maxspeed = 0;
this.engine = 0;
}
public Car (String color, int weight,
int state, int fuel, int Maxspeed
) {
this.color = color;
this.weight = weight;
this.state = state;
this.fuel = fuel;
this.Maxspeed = Maxspeed;
}
public String getColor() { return this.color; }
public int getweight() { return this.weight; }
public int getstate() { return this.state; }
public int getfuel() { return this.fuel; }
public int getMaxspeed() { return this.Maxspeed; }
public int getengine() { return this.engine; }
public void setColor( String color ){
this.color = color;
}
public void setweight( int weight ){
this.weight = weight;
}
public void setstate( int state ){
this.state = state;
}
public void setfuel( int fuel ){
this.fuel = fuel;
}
public void setMaxspeed( int Maxspeed ){
this.Maxspeed = Maxspeed;
}
public void setengine(int engine){
this.engine = engine;
}
public void showdata() {
System.out.println( "\nCar's color is: " + this.getColor() );
System.out.println( "Car's weight is: " + this.getweight() );
System.out.println( "State: " + this.getstate() );
System.out.println( "Fuel: " + this.getfuel());
System.out.println( "Max speed: " + this.getMaxspeed());
}
public void accelerate( int speed ){
if( this.getstate() == 0 || this.getstate() == 3 ||
this.getstate() == 4 || this.getMaxspeed() < speed )
{
System.out.println("\nCar cannot accelerate...");
}
else {
System.out.println("\nCar is accelerating...");
this.setfuel(this.getfuel()-2);
this.setstate(2);
if( this.getfuel() <= 0 ) {
this.setstate(4);
}
}
}
public void crash() {
this.setstate(3);
System.out.println("\nCrash!!!");
}
public void stop() {
this.setstate(1);
System.out.println("\nCar has stopped.");
}
public void addfuel(int fuel) {
if(this.getstate() == 0 || this.getstate() == 4){
this.setfuel(this.getfuel()+ fuel);
}
else {
System.out.println("You can't add fuel.");
}
}
public void repair() {
if(this.getstate() == 3){
this.setstate(1);
System.out.println("The car has been repaired");
}
else{
System.out.println("The car is not broken");
}
}
}
My Main:
import java.util.Scanner;
public class aaa {
public static void main (String args []) {
Car x[] = new Car[2];
int keep=1;
int counter = 0;
int counter_stopped = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxIndex = 0;
int maxweight = 0;
int index_engine = 0;
int min_engine = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length; i++) {
String color;
int weight;
int fuel;
int Maxspeed;
int engine;
x[i] = new Car();
System.out.print("\nEnter car color " + (i + 1) + ": ");
color = input.next();
System.out.print("Enter car weight " + (i + 1) + ": ");
weight = input.nextInt();
System.out.print("Enter car fuel " + (i + 1) + ": ");
fuel = input.nextInt();
System.out.print("Enter car max speed " + (i + 1) + ": ");
Maxspeed = input.nextInt();
System.out.print("Enter car engine weight " + (i + 1) + ": ");
engine = input.nextInt();
x[i].setColor(color);
x[i].setweight(weight);
x[i].getstate();
x[i].setfuel(fuel);
x[i].setMaxspeed(Maxspeed);
x[i].setengine(engine);
}
for(int i = 0; i < x.length; i++) {
int state;
System.out.print("\nEnter car state " + (i + 1) + ": ");
state = input.nextInt();
x[i].setstate(state);
while(state > 4 || state < 0){
System.out.print("state not valid.\nTry again: ");
state = input.nextInt();
x[i].setstate(state);
}
do {
keep = menu();
switch( keep ) {
case 1:
accelerate(x[i]);
break;
case 2:
stop(x[i]);
break;
case 3:
crash(x[i]);
break;
case 4:
addfuel(x[i]);
break;
case 5:
repair(x[i]);
break;
case 6:
x[i].showdata();
}
} while(keep != 7);
if(x[i].getstate() == 4 || x[i].getfuel() <= 0){
counter += 1;
}
if(x[i].getstate() == 1){
counter_stopped += 1;
}
int weight = x[i].getweight();
if(weight > max){
maxweight = weight;
maxIndex = i;
}
int weightengine = x[i].getengine();
if(weightengine < min){
min_engine = weightengine;
index_engine = i;
}
}
System.out.println("\nSUMMARY");
System.out.println("Amount of cars with no fuel: " + counter);
System.out.println("Amount of stopped cars: " + counter_stopped);
System.out.println("Heaviest car: " + maxIndex);
System.out.println("Car with the smallest engine: " + index_engine);
System.out.println("=============================================");
}
public static int menu() {
int option = 0;
Scanner s = new Scanner(System.in);
System.out.println("\n1. Accelerate Car ");
System.out.println("2. Stop Car ");
System.out.println("3. Crash Car ");
System.out.println("4. Add fuel ");
System.out.println("5. Repair ");
System.out.println("6. Show data ");
System.out.println("7. Exit ");
System.out.println("=============================================");
System.out.print("Choose an option : ");
option = s.nextInt();
System.out.println("=============================================");
return option;
}
public static void accelerate(Car myCar){
Scanner input = new Scanner(System.in);
int s;
System.out.print("Enter speed: ");
s = input.nextInt();
myCar.accelerate(s);
//myCar.showdata();
}
public static void stop(Car myCar){
myCar.stop();
}
public static void crash(Car myCar){
myCar.crash();
}
public static void addfuel(Car myCar){
int fuel;
Scanner input = new Scanner(System.in);
System.out.print("Amount to add: ");
fuel = input.nextInt();
myCar.addfuel(fuel);
}
public static void repair(Car myCar){
myCar.repair();
}
}
Now, when I compile and test which engine or car is smaller or heaviest, I get the number 1 as result.
The most obvious issue is
if(weight > max){
maxweight = weight;
You are comparing max and weight, but then seeting maxweight. Also, I suggest you prefer Math.max(int, int) and Math.min(int, int) like
max = Math.max(max, weight);
min = Math.min(min, weight);
Edit To store the index of the min and max value you could initialize max and min to 0 and loop from index 1 to x.length. That might look something like
int max = 0;
int min = 0;
for (int i = 1; i < x.length; i++) {
if (x[i].getweight() > x[max].getweight) {
max = i;
} else if (x[i].getweight() < x[min].getweight) {
min = i;
}
}

try catch issue Java OOP (Bank System Application)

I've fixed the duplicating error by re-writting the application in another way but now stuck on try catch to not let user enter undefended entry just letting him add the valid numbers in my switch case
import java.util.Scanner;
public class BankSystem {
private Account acc;
Scanner Input;
public BankSystem() {
this.acc = new Account(100);
Input = new Scanner(System.in);
}
public static void main(String[] args) {
BankSystem bs = new BankSystem();
bs.main();
}
public void main() {
while (true) {
try {
System.out.println("==========================");
System.out.println("========Main Menu=========");
System.out.println("Please Enter Your Choice: ");
System.out.println("1=> Main");
System.out.println("2=> New Account");
System.out.println("3=> Deposit Money");
System.out.println("4=> Withdraw Money");
System.out.println("5=> Personal Balance");
System.out.println("6=> Money Transfer");
System.out.println("7=> Full Customer Report:");
System.out.println("8=> Delete Account");
System.out.println("9=> Calculate Interest");
System.out.println("0=> Exit");
System.out.print("=> ");
int Choice = Input.nextInt();
switch (Choice) {
case 1:
main();
break;
case 2:
addAccount();
break;
case 3:
depositMoney();
break;
case 4:
withdrawMoney();
break;
case 5:
personalBalance();
break;
case 6:
transferMoney();
break;
case 7:
fullReport();
break;
case 8:
deleteAccount();
break;
case 9:
break;
case 0:
System.out
.println("Thanks For Using this App we're Looking forward to see You Again :)");
System.exit(0);
break;
default:
System.out.println("Entry is not valid.\n");
break;
}
} catch (Exception e) {
System.out.println("================================");
System.err.println("! You Have Entered Wrong Value !");
System.out.println("================================");
// break;
}
}
}
private void addAccount() {
System.out.println("Enter The Account Number:");
int acc = Input.nextInt();
System.out.println("Enter The Account First Name:");
String name = Input.next();
System.out.println("Enter The Account Last Name:");
String Sname = Input.next();
System.out.println("Enter The Amount:");
double bal = Input.nextDouble();
Customer cust = new Customer(acc, name, Sname, bal);
this.acc.insert(cust);
}
private void depositMoney() {
System.out.println("Enter Account Number:");
int acc = Input.nextInt();
System.out.println("Enter The Amount:");
double amount = Input.nextDouble();
if (amount <= 0)
System.out.println("The amount can not be negative or zero.");
else
this.acc.depositMoney(acc, amount);
}
private void withdrawMoney() {
System.out.println("Enter Account Number:");
int acc = Input.nextInt();
System.out.println("Enter The Amount:");
double amount = Input.nextDouble();
if (amount <= 0)
System.out.println("The amount can not be negative or zero.");
else
this.acc.withdrawMoney(acc, amount);
}
private void transferMoney() {
System.out.println("Enter The Sender Account Number:");
int fromAcc = Input.nextInt();
System.out.println("Enter The Receiver Account Number:");
int toAcc = Input.nextInt();
System.out.println("Enter The Amount:");
double amount = Input.nextDouble();
this.acc.transferMoney(fromAcc, toAcc, amount);
}
private void personalBalance() {
System.out.println("Enter The Account Number:");
int acc = Input.nextInt();
this.acc.personalDisplay(acc);
}
private void deleteAccount() {
System.out.println("Enter The Account Number:");
int acc = Input.nextInt();
this.acc.delete(acc);
}
private void fullReport() {
this.acc.displayList();
}
}
class Customer {
private int accNum;
private String name;
private String Sname;
private double balance;
public Customer(int a, String n, String Sn, double amount) {
accNum = a;
name = n;
Sname = Sn;
balance = amount;
}
public String getname() {
return name;
}
public String getSname() {
return Sname;
}
public int getaccNum() {
return accNum;
}
public double getBalance() {
return balance;
}
public void personalDisplay() {
System.out.println(this.getname() + " " + this.getSname()
+ "'s balance is " + this.getBalance());
}
public void deposit(double amount) {
if (amount <= 0)
System.out.println("The amount must be bigger than zero.");
else
this.balance += amount;
}
public void display() {
System.out.println(this.getaccNum() + "\t" + this.getname() + "\t"
+ this.getSname() + "\t" + this.getBalance());
}
public void withdraw(double amount) {
if (this.balance >= amount)
this.balance -= amount; // Subtract "amount" from balance
}
}
class Account {
private Customer[] Array;
private int nElem;
public Account(int max) {
Array = new Customer[max];
nElem = 0;
}
public boolean find(int data) {
int LowBoun = 0;
int HighBoun = nElem;
int Now;
while (true) {
Now = (LowBoun + HighBoun) / 2;
if (Array[Now].getaccNum() == data)
return true;
else {
if (Array[Now].getaccNum() < data)
LowBoun = Now + 1;
else
HighBoun = Now - 1;
}
if (LowBoun > HighBoun)
return false;
}
}
public void insert(Customer newData) {
int i, j;
if (!find(newData.getaccNum())) {
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() > newData.getaccNum())
break;
for (j = nElem; j > i; j--)
Array[j] = Array[j - 1];
Array[j] = newData;
nElem++;
} else
System.out.println("the number is exist!");
}
public boolean delete(int acc) {
int i;
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() == acc)
break;
if (i == nElem)
return false;
else {
for (int j = i; j < nElem; j++) {
Array[j] = Array[j + 1];
}
nElem--;
return true;
}
}
public void transferMoney(int fromAcc, int toAcc, double amount) {
int i, j;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == fromAcc)
break;
}
for (j = 0; j < nElem; j++) {
if (Array[j].getaccNum() == toAcc)
break;
}
Array[i].withdraw(amount);
Array[j].deposit(amount);
}
public void personalDisplay(int acc) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].personalDisplay();
}
public void depositMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].deposit(amount);
}
public void withdrawMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].withdraw(amount);
}
public void displayList() {
for (int i = 0; i < nElem; i++) {
this.Array[i].display();
}
}
}
I think you need to implement the comparable interface in the Customer class and
then do this
if(!c.contains(customer)){
c[numberOfCustomers]=customer;
numberOfCustomers++;
}
You can convert c from array to list if contains is not available on the array using Arrays.asList() method.
This might be helpful to you.
I've Solved My Code in a different way :
import java.util.*;
public class BankSystem {
private Account accArr;
Scanner Input;
public BankSystem() {
accArr = new Account(100);
Input = new Scanner(System.in);
}
public static void main(String[] args) {
BankSystem bs = new BankSystem();
bs.main();
}
public void main() {
int Choice = 1;
while (Choice != 0) {
System.out.println("==========================");
System.out.println("Please Enter Your Choice: ");
System.out.println("1=> Main");
System.out.println("2=> New Account");
System.out.println("3=> Deposit Money");
System.out.println("4=> Withdraw Money");
System.out.println("5=> Personal Balance");
System.out.println("6=> Money Transfer");
System.out.println("7=> Full Customers Report:");
System.out.println("8=> Delete Account");
System.out.println("0=> Exit");
System.out.println("==========================");
System.out.print("=> ");
try {
Choice = Input.nextInt();
} catch (InputMismatchException e) {
System.err.print("! You Have Entered Wrong Value !\n");
Input.next();
}
switch (Choice) {
case 1:
System.out.println("========Main Menu=========");
main();
break;
case 2:
System.out.println("========New Account=========");
System.out.print("Enter The Account Number:");
int acc = Input.nextInt();
System.out.print("Enter The Account First Name:");
String name = Input.next();
System.out.print("Enter The Account Last Name:");
String Sname = Input.next();
System.out.print("Enter The Amount:");
double bal = Input.nextDouble();
Customer cust = new Customer(acc, name, Sname, bal);
this.accArr.insert(cust);
break;
case 3:
System.out.println("========Deposit Money=========");
System.out.print("Enter Account Number:");
acc = Input.nextInt();
System.out.print("Enter The Amount:");
double amount = Input.nextDouble();
if (amount <= 0)
System.out
.println("The amount can not be negative or zero.");
else
this.accArr.depositMoney(acc, amount);
break;
case 4:
System.out.println("========Withdraw Money=========");
System.out.print("Enter Account Number:");
acc = Input.nextInt();
System.out.print("Enter The Amount:");
amount = Input.nextDouble();
if (amount <= 0)
System.out
.println("The amount can not be negative or zero.");
else
this.accArr.withdrawMoney(acc, amount);
break;
case 5:
System.out.println("========Personal Balance=========");
System.out.print("Enter The Account Number:");
acc = Input.nextInt();
this.accArr.personalDisplay(acc);
break;
case 6:
System.out.println("========Money Transfer=========");
System.out.print("Enter The Sender Account Number:");
int fromAcc = Input.nextInt();
System.out.print("Enter The Receiver Account Number:");
int toAcc = Input.nextInt();
System.out.print("Enter The Amount:");
amount = Input.nextDouble();
this.accArr.transferMoney(fromAcc, toAcc, amount);
break;
case 7:
System.out.println("========Full Customers Report=========");
System.out.println("Ac Num.\tName\tSurname\tBalance");
this.accArr.displayList();
break;
case 8:
System.out.println("========Delete Account=========");
System.out.print("Enter The Account Number:");
acc = Input.nextInt();
this.accArr.delete(acc);
break;
case 9:
break;
case 0:
System.out
.println("Thanks For Using this App we're Looking forward to see You Again :)");
System.exit(0);
break;
default:
System.out.println("Entry is not valid.\n");
break;
}
}
}
}
class Customer {
private int accNum;
private String name;
private String Sname;
private double balance;
public Customer(int a, String n, String Sn, double amount) {
accNum = a;
name = n;
Sname = Sn;
balance = amount;
}
public String getname() {
return name;
}
public String getSname() {
return Sname;
}
public int getaccNum() {
return accNum;
}
public double getBalance() {
return balance;
}
public void personalDisplay() {
System.out.println(getname() + " " + getSname() + "'s Balance is "
+ getBalance() + "$");
}
public void deposit(double amount) {
this.balance += amount;
System.out.println(amount + "$ has been Deposited");
}
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.println(amount + "$ has been Withdrawed");
} else
System.out.println("Insufficient Balance " + balance);
}
public void display() {
System.out.println(getaccNum() + "\t" + getname() + "\t" + getSname()
+ "\t" + getBalance() + "$");
}
}
class Account {
private Customer[] Array;
private int nElem;
public Account(int max) {
Array = new Customer[max];
nElem = 0;
}
public void insert(Customer newData) {
int i, j;
if (newData.getaccNum() <= 0)
System.out.println("The Account ID can't be Negative");
else
if (find(newData.getaccNum()))
System.out.println("This User is already exist!");
else {
if (newData.getBalance() < 0)
System.out.println("Amount can't be Negative!");
else {
if (nElem == (Array.length - 1))
System.out.println("Slots are Full");
else {
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() > newData.getaccNum())
break;
for (j = nElem; j > i; j--)
Array[j] = Array[j - 1];
Array[i] = newData;
nElem++;
}
}
}
}
public boolean delete(int del) {
int i;
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() == del)
break;
if (i == nElem)
return false;
else {
for (int j = i; j < nElem; j++) {
Array[j] = Array[j + 1];
}
nElem--;
System.out.println("Customer " + del + " has been Deleted !");
return true;
}
}
public boolean find(int accountId) {
if (nElem == 0) {
return false;
}
int LowBoun = 0;
int HighBoun = nElem - 1;
int now;
while (true) {
now = (LowBoun + HighBoun) / 2;
if (this.Array[now].getaccNum() == accountId)
return true;
else {
if (Array[now].getaccNum() < accountId)
LowBoun = now + 1;
else
HighBoun = now - 1;
}
if (LowBoun > HighBoun)
return false;
}
}
public void transferMoney(int fromAcc, int toAcc, double amount) {
int i, j;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == fromAcc)
break;
}
for (j = 0; j < nElem; j++) {
if (Array[j].getaccNum() == toAcc)
break;
}
Array[i].withdraw(amount);
Array[j].deposit(amount);
System.out.println(amount + "$ has been Transfered to Account Number:'"
+ toAcc + "'");
}
public void personalDisplay(int acc) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].personalDisplay();
}
public void depositMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].deposit(amount);
}
public void withdrawMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].withdraw(amount);
}
public void displayList() {
for (int i = 0; i < nElem; i++) {
this.Array[i].display();
}
}
}

Counter in while loop does not increase

I need to develop a scholarship application in Java. I need to print the successful application in output.
Why a counter in this code does not increase if I for a second person?
import java.util.Scanner;
import java.util.LinkedList;
public class Main
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
Application a = new Application();
LinkedList lList = new LinkedList();
boolean bEligible = false;
int scholarship;
int scholarshipAmount = 500000;
int setiStudyLevel;
int counter;
while(scholarshipAmount != 0)
{
counter = 1;
System.out.println("");
System.out.println("**Welcome to scholarship applications offered by Smart Foundation**");
System.out.println("");
System.out.println("");
System.out.println("Please Enter Your Name");
a.setsName(input.next());
System.out.println("1–Pre Diploma, 2–Diploma, 3–Degree");
System.out.println("Please Enter Your Study Level");
a.setiStudyLevel(input.nextInt());
System.out.println("Please Enter Your Personality Score");
a.setiPersonalityScore(input.nextInt());
System.out.println("Please Enter Your Parents Income");
a.setdParentsIncome(input.nextDouble());
String sName = a.getsName();
int iStudyLevel = a.getiStudyLevel();
int iPersonalityScore = a.getiPersonalityScore();
double dParentsIncome = a.getdParentsIncome();
if (iStudyLevel == 1)
{
scholarship = 15000;
scholarshipAmount = scholarshipAmount - scholarship;
}
else if (iStudyLevel == 2)
{
scholarship = 50000;
scholarshipAmount = scholarshipAmount - scholarship;
}
else if (iStudyLevel == 3)
{
scholarship = 500000;
scholarshipAmount = scholarshipAmount - scholarship;
}
System.out.println("");
System.out.println("");
System.out.println("*****Result*****");
System.out.println("Name:"+sName);
System.out.println("1–Pre Diploma, 2–Diploma, 3–Degree");
System.out.println("Study Level:"+iStudyLevel);
System.out.println("Personality Score:"+iPersonalityScore);
System.out.println("Parents Income:"+dParentsIncome);
if(iPersonalityScore <=90)
{
if(dParentsIncome >=3000)
{
System.out.println("YOU ARE NOT ELIGIBLE FOR SCHOLARSHIP ");
}
else
{
System.out.println("YOU ARE ELIGIBLE FOR SCHOLARSHIP ");
bEligible = true;
}
}
else
{
System.out.println("YOU ARE ELIGIBLE FOR SCHOLARSHIP ");
}
System.out.println("");
System.out.println( "RM"+(scholarshipAmount)+" left!!");
System.out.println("");
if (scholarshipAmount <= 0)
{
System.out.println(" Scholarship Quota is Full!");
}
counter++;
System.out.println(counter);
}
}
}
The problem is that you reset your counter to 1 on each loop
Change this:
while(scholarshipAmount != 0)
{
counter = 1;
to this
int counter = 1;//or maybe 0
while(scholarshipAmount != 0)
{
Your loop should be,
while(scholarshipAmount > 0)
{
//remaining code

How to read lines from a file and assign the lines to an array?

Currently, I'm trying to read in a .dat file and assign various lines into an array. The file will provide items like "a100" and "q80" which I will have to separate into categories by letter and then have different grades as an array for each category. Right now, this is what I have, but I'm getting a lot of run-time errors when I try various things. Is there something I'm missing here?
Some of the errors I'm having:
When I execute case 'P', it prints this out: WeightedGrades#13105f32
When I try to execute cases C, A or D, this happens: Exception in thread "main" java.lang.NoSuchMethodError: WeightedGrades.deleteGrade(Ljava/lang/String;)Z
WeightedGrades class:
public class WeightedGrades {
private String name;
private int numGrades;
private String[] grades;
public static final double ACTV_WT = 0.05, QUIZ_WT = 0.10, PROJ_WT = 0.25, EXAM_WT = 0.30, FINAL_EXAM_WT = 0.30;
public WeightedGrades(String nameIn, int numGradesIn, String[] gradesIn) {
name = nameIn;
numGrades = numGradesIn;
grades = gradesIn;
}
public String getName() {
return name;
}
public int getNumGrades() {
return numGrades;
}
public String[] getGrades() {
return grades;
}
public double[] gradesByCategory(char categoryChar) {
int count = 0;
for (int i = 0; i < grades.length; i++) {
if (categoryChar == grades[i].charAt(0)) {
count++;
}
}
double[] gradesNew = new double[count];
count = 0;
for( int i = 0; i < numGrades; i++) {
if (categoryChar == grades[i].charAt(0)) {
gradesNew[count] = Double.parseDouble(grades[i].substring(1));
count++;
}
}
return gradesNew;
}
public String toString() {
String result = "\tStudent Name: " + getName()
+ "\n\tActivities: " + gradesByCategory('A')
+ "\n\tQuizzes: " + gradesByCategory('Q')
+ "\n\tProjects: " + gradesByCategory('P')
+ "\n\tExams: " + gradesByCategory('E')
+ "\n\tFinal Exam: " + gradesByCategory('F')
+ "\n\tCourse Average: " + courseAvg();
return result;
}
public void addGrade(String newGrade) {
if (numGrades >= grades.length) {
increaseGradesCapacity();
}
grades[numGrades] = newGrade;
numGrades++;
}
public boolean deleteGrade(String gradeDelete) {
boolean delete = false;
int deleteIndex = -1;
for (int i = 0; i < numGrades; i++) {
if (gradeDelete.charAt(0) == grades[i].charAt(0) &&
Double.parseDouble(gradeDelete.substring(1))
== Double.parseDouble(grades[i].substring(1))) {
deleteIndex = i;
}
}
if (deleteIndex > -1) {
for (int i = deleteIndex; i < numGrades - 1; i++) {
grades[i] = grades[i + 1];
}
grades[numGrades - 1] = "";
numGrades--;
return true;
}
else {
return false;
}
}
public void increaseGradesCapacity() {
String[] temporary = new String[grades.length + 1];
for (int i = 0; i < grades.length; i++) {
temporary[i] = grades[i];
}
grades = temporary;
}
public double average(double[] newArray) {
if (newArray.length == 0) {
return 0.0;
}
double sum = 0;
double average = 0;
for ( int i = 0; i < newArray.length; i++) {
sum += newArray[i];
average = sum / newArray.length;
}
return average;
}
public double courseAvg() {
double actvAvg = 0.0;
double quizAvg = 0.0;
double projAvg = 0.0;
double examAvg = 0.0;
double finalAvg = 0.0;
double avg = 0.0;
if (!numGrades.length == 0) {
avg = actvAvg * ACTV_WT + quizAvg * QUIZ_WT + projAvg * PROJ_WT + examAvg * EXAM_WT + finalAvg * FINAL_EXAM_WT;
}
return avg;
}
}
Second class
import java.util.Scanner;
import java.io.IOException;
public class WeightedGradesApp {
public static void main(String[] args) throws IOException {
String name = "";
int numGrades = 0;
String[] grades = new String[13];
String code = "";
String gradeAdd = "";
String gradeDelete = "";
String categoryIn = "";
WeightedGrades student = new WeightedGrades(name, numGrades, grades);
Scanner userInput = new Scanner(System.in);
if (args == null) {
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
return;
}
else {
System.out.println("File read in and WeightedGrades object created.");
System.out.println("");
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("C - Print Category");
System.out.println("A - Add Grade");
System.out.println("D - Delete Grade");
System.out.println("Q - Quit ");
do {
System.out.print("Enter Code [P, C, A, D, or Q]: ");
code = userInput.nextLine();
if (code.length() == 0) {
continue;
}
code = code.toUpperCase();
char codeChar = code.charAt(0);
switch (codeChar) {
case 'P':
System.out.println(student.toString());
break;
case 'C':
System.out.print(" Category: ");
categoryIn = userInput.nextLine();
char categoryChar = categoryIn.charAt(0);
System.out.println(student.gradesByCategory(categoryChar));
break;
case 'A':
System.out.print(" Grade to add: ");
gradeAdd = userInput.nextLine();
student.addGrade(gradeAdd);
break;
case 'D':
System.out.print(" Grade to delete: ");
gradeDelete = userInput.nextLine();
boolean isDeleted = student.deleteGrade(gradeDelete);
if (isDeleted) {
System.out.println(" Grade deleted");
}
else {
System.out.println(" Grade not found");
}
break;
case 'Q':
break;
default:
}
} while (!code.equalsIgnoreCase("Q"));
}
}
}
For starters your code as is doesn't compile due to the line
if (!numGrades.length == 0) {
This is because numGrades is an int it is a primative type and therefore does not have any property length. I'm assuming what you want here is
if (numGrades != 0) {
Also as I mentioned you are not dealing with reading in the file, you supply the file name but never actually read it, I suggest you look at the Java tutorial on File IO
On this note you do the check args == null this will not check that no args are supplied, try it. what you want is args.length == 0
On your other error I have no idea how you even produced that... I'm assuming it is using an older compiled version of the class where the methods have not being written.

Categories