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();
}
}
}
Related
I have an assignment where I have to create an ATM. The program is running, but it seems as if I have an issue because my balance continuously reads $100. I'm not sure where I went wrong in the code. There might be something wrong in my if statement, or in my switch, but I am not sure what I am doing wrong. I have looked over this code for hours, but I seem to just miss the error.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ATMDemo {
public static void main(String[] args) throws IOException {
Account[] accounts = new Account[10];
for(int i=0; i<10; i++) {
accounts[i] = new Account(100,5);
}
System.out.println("Enter Id (0-9)");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int id = Integer.parseInt(br.readLine());
while(!(id>=0 && id <10)) {
System.out.println("Wrong Id, enter again");
id = Integer.parseInt(br.readLine());
}
printMenu();
int c = Integer.parseInt(br.readLine());
while (c!=4) {
switch (c) {
case 1:
System.out.println("Balance : " + accounts[id].getBalance());
break;
case 2:
System.out.println("Enter amount");
double amt = Double.parseDouble(br.readLine());
accounts[id].withdraw(amt);
break;
case 3:
System.out.println("Enter amount");
double amt1 = Double.parseDouble(br.readLine());
accounts[id].deposit(amt1);
break;
}
}
if (c==4) {
System.out.println("Program exited!!!");
}
}
public static void printMenu() {
System.out.println("Enter a choice: \n " +
"1) check balance,\n" +
"2) withdraw,\n" +
"3) deposit, and \n" +
"4) exit");
}
}
class Account {
double balance;
double transaction[][];
int tCount;
int size;
public Account(double balance, int size) {
this.balance = balance;
this.transaction = new double[size][2];
this.tCount = 0;
this.size= size;
}
public void deposit(double amt) {
if(amt>0) {
transact(amt);
} else {
System.out.println("Amount should be > 0 to deposit");
}
}
public void withdraw(double amt) {
if(amt<=balance) {
transact(amt*-1);
} else {
System.out.println("Insufficient Balance");
}
}
public void print() {
for(int i=0; i<tCount; i++) {
System.out.println(transaction[i][0] +", "+ transaction[i][1]);
}
System.out.println("Current available balance :"+balance);
}
public int count() {
return transaction.length;
}
public int count(double base) {
int count = 0;
for(int i=0; i<tCount; i++) {
if(transaction[i][0]<0) {
double amt = -1 * transaction[i][0];
if(amt > base) {
count++;
}
}
}
return count;
}
public void transact(double val) {
if(tCount+1>size)
resize();
balance = balance + val;
transaction[tCount][0] = val;
transaction[tCount][1] = balance;
tCount++;
}
public void resize() {
double[][] tNew = new double[this.size+10][2];
for(int i=0; i<tCount; i++) {
tNew[i] = transaction[i];
}
this.size = this.size + 10;
this.transaction = tNew;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double[][] getTransaction() {
return transaction;
}
public void setTransaction(double[][] transaction) {
this.transaction = transaction;
}
}
Move
printMenu();
int c = Integer.parseInt(br.readLine());
just below
while (c!=4) {
That would make the application pause and ask for input after it performs and action. Right now it just asks once, c becomes 1 and the endless while loops just starts because the value of c is never changed again.
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'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;
}
}
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;
}
}
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.