How to access an object parameter from a hashmap value - java

I am trying to access the accOpBalance parameter from the Account method stored in the HashMap. I want to be able to change this value based on transaction type and store it again. I also want to save the the 6 most recent transactions fot the account but not sure how to approach the problem. I hope this describes the problem well enough. Im still very new to this and would love feedback on my code aswell.
public class BankingSystem{
static int accNum;
static String accName;
static String accAdd;
static String accOpDate;
static double accOpBalance;
int option = 0;
static Scanner keyboard = new Scanner(System.in);
static HashMap<Integer, Account> accounts = new HashMap<Integer, Account>(Map.of(
accNum, new Account(accNum, accName, accAdd, accOpDate, accOpBalance)
));
public BankingSystem() {
}
public static void main(String[] args) {
BankingSystem bankingSystem = new BankingSystem();
int option;
do{
option = mainMenu(keyboard);
System.out.println();
if(option == 1){
bankingSystem.createAccount(keyboard);
} else if (option == 2) {
bankingSystem.showAccounts();
} else if (option == 4) {
bankingSystem.deleteAccount();
}
}while(option != 5);
}
public void createAccount(Scanner keyboard) {
do{
System.out.println("-----------------------------------------------");
System.out.print("Please enter 1 to continue or -1 to exit: ");
option = keyboard.nextInt();
switch (option) {
case 1 -> {
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
System.out.println("-----------------------------------------------");
System.out.print("Please enter the new account number: ");
accNum = keyboard.nextInt();
newAccount.setAccNum(accNum);
System.out.print("Please enter the name of the account holder: ");
accName = keyboard.next();
newAccount.setAccName(accName);
System.out.print("Please enter the address of the account holder: ");
accAdd = keyboard.next();
newAccount.setAccAdd(accAdd);
System.out.print("Please enter the accounts open date: ");
accOpDate = keyboard.next();
newAccount.setAccOpDate(accOpDate);
System.out.print("Please enter the starting balance: ");
accOpBalance = keyboard.nextDouble();
newAccount.setAccOpBalance(accOpBalance);
accounts.put(accNum, new Account(accNum, accName, accAdd, accOpDate, accOpBalance));
}
case 2 -> {
System.out.println("Please type -1 the exit create account menu: ");
option = keyboard.nextInt();
}
}
}while (option != -1);
}
public void showAccounts() {
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
}
}
public void deleteAccount(){
int key;
option = 0;
do {
System.out.println("-----------------------------------------------");
System.out.print("Please enter 1 to continue or -1 to exit: ");
option = keyboard.nextInt();
switch (option) {
case 1 -> {
System.out.print("-----------------------------------------------");
System.out.print("Please enter the Account number of the" + "\n" +
" the account you wish to delete");
System.out.print("-----------------------------------------------");
key = keyboard.nextInt();
accounts.remove(key);
}
case 2 -> {
System.out.println("Please type -1 the exit delete account menu: ");
option = keyboard.nextInt();
}
}
}while (option != -1);
}
public static int mainMenu(Scanner keyboard){
int menuOption;
System.out.println("Welcome to the bank of Cal");
System.out.println("-----------------------------------------------");
System.out.println("Main Menu" + "\n" + "Please select option:");
System.out.println("1. Create Account");
System.out.println("2. Display Accounts");
System.out.println("3. Deposit/Withdraw");
System.out.println("4. Delete Account");
System.out.println("5. Exit Program");
System.out.println("-----------------------------------------------");
do{
menuOption = keyboard.nextInt();
}while(menuOption <1 || menuOption >5);
return menuOption;
}
public class Account {
private int accNum;
private String accName;
private String accAdd;
private String accOpDate;
private double accOpBalance;
Scanner getDetails = new Scanner(System.in);
public Account(int theAccNum, String theAccName, String theAccAdd, String theAccOpDate, double theAccOpBalance){
accNum = theAccNum;
accName = theAccName;
accAdd = theAccAdd;
accOpDate = theAccOpDate;
accOpBalance = theAccOpBalance;
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public String getAccName(){
return accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public String getAccAdd(){
return accAdd;
}
public void setAccOpDate(String accOpDate){
this.accOpDate = accOpDate;
}
public String getAccOpDate(){
return accOpDate;
}
public void setAccOpBalance(double accOpBalance){
this.accOpBalance = accOpBalance;
}
public double getAccOpBalance(){
return accOpBalance;
}
#Override
public String toString() {
return "\n" + "Account Number: " + accNum + "\n" + "Name: " + accName +
"\n" + "Account Holder Address: " + accAdd + "\n" +"Account open date: "
+ accOpDate + "\n" + "Account balance: " + accOpBalance;
}
}

Related

Is it possible to create a text file and then on the same run or runtime of the code also read and write in these files? Java

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

Cannot invoke contains(int) on the primitive type int

I'm having a problem with case 4. I'm trying to find a voter using ID. It's public and it says Cannot invoke contains(int) on the primitive type int. Why is that? The Id is literally public but I don't know the problem.
All I'm trying to do is to find the Id of the voter.
public class Voters {
public static HashSet<Voter> voters = new HashSet<>();
public static void main(String[] args) throws IOException {
while (true) {
System.out.println("1. Add New Voter");
System.out.println("2. List All Voters");
System.out.println("3. Find a Voter By Name");
System.out.println("4. Get information about specific voter");
System.out.println("5. Exit");
Scanner scanner = new Scanner(System.in);
int chosen = scanner.nextInt();
switch (chosen) {
case 1:
System.out.print("National ID Number: ");
int idNum = scanner.nextInt();
System.out.print("\nName: ");
String name = scanner.next();
System.out.print("\nMale Relative: ");
String maleRelative = scanner.next();
System.out.print("\nAge: ");
int age = scanner.nextInt();
System.out.print("\nAddress: ");
String address = scanner.next();
System.out.print("\nProvince: ");
String province = scanner.next();
System.out.println("");
Voter voter = new Voter(idNum, name, maleRelative, age, address, province);
voters.add(voter);
FileWriter fileWriter = new FileWriter("C:\\Users\\YourPcName\\Desktop\\voters.txt");
fileWriter.append("\n").append(voter.toString());
fileWriter.flush();
fileWriter.close();
break;
case 2:
for (Voter v : voters) {
System.out.println(v);
}
break;
case 3:
System.out.print("Name: ");
Scanner ss = new Scanner(System.in);
String n = ss.nextLine();
System.out.println();
for (Voter v : voters) {
if (v.name.contains(n)) {
System.out.println(v);
break;
}
}
break;
case 4:
System.out.print("Id: ");
Scanner nn = new Scanner(System.in);
int s = nn.nextInt();
System.out.println();
for (Voter v : voters) {
if (v.nationalIdNumber.contains(s)) {
System.out.println(v);
break;
}
}
break;
case 5:
System.exit(0);
break;
default:
}
}
}
static class Voter {
public int nationalIdNumber;
public String name;
public String maleRelativeName;
public int age;
public String address;
public String province;
public Voter(int nationalIdNumber, String name, String maleRelativeName, int age, String address,
String province) {
this.nationalIdNumber = nationalIdNumber;
this.name = name;
this.maleRelativeName = maleRelativeName;
this.age = age;
this.address = address;
this.province = province;
}
public String toString() {
return "Id: " + nationalIdNumber + " Name: " + name + " Male Relative: " + maleRelativeName + " Age: "
+ age + " Address: " + address + " Province: " + province;
}
}
nationalIdNumber is of type int It does not have any methods. What are you trying to do? Maybe that line should read
if (v.nationalIdNumber == s) {
? I dont't know. Give us some more context.

Using Linked List as the output?

I'm trying to write a bank account that asks the user if they want to see records, remove records, and other stuff. This is what I'm trying to produce
My program is nearly done the only problem I'm having is getting the output. I'm getting some weird error when i tried producing the output. When the output works. I'll put it inside a linked list.
public class Bank
{
public static void main(String args[]){
ArrayList<Customer> accounts = new ArrayList<Customer>();
Customer customer1 = new Customer(1, "Savings", "Dollars", 800);
Customer customer2 = new Customer(2, "Checking", "Euro", 1900);
Customer customer3 = new Customer(3, "Checking", "Pound", 8000);
accounts.add(customer1);
accounts.add(customer2);
accounts.add(customer3);
int customerID=4;
String choice;
int deposit;
int withdraw;
Scanner in = new Scanner(System.in);
Customer operation = new Customer();
boolean flag = true;
String accountType;
String currencyType;
int balance;
while(flag){
System.out.println("Select a choice:");
System.out.println("1. Existing customer");
System.out.println("2. New customer");
System.out.println("3. Quit");
String input = in.next();
//existing user
if(input.equals("1")){
System.out.println("Enter CustomerID: ");
customerID = in.nextInt();
System.out.println("Would you like to: ");
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Display account info ");
System.out.println("4. Check balance ");
choice = in.next();
if(choice.equals("1")){
System.out.println("How much would you like to deposit?");
deposit = in.nextInt();
operation.deposit(deposit);
}
else if (choice.equals("2")){
System.out.println("How much would you like to withdraw?");
withdraw = in.nextInt();
operation.withdraw(withdraw);
}
else if (choice.equals("3")){
operation.display(accounts.get(customerID));
}
else if (choice.equals("4"))
operation.balance(accounts.get(customerID));
else
System.out.println("Invalid");
}
//new user
else if(input.equals("2")){
//add new user to arraylist
int newID = customerID + 1;
System.out.println("Enter account type: ");
accountType = in.next();
System.out.println("Enter currency type: ");
currencyType = in.next();
System.out.println("Enter initial balance: ");
balance = in.nextInt();
System.out.println("Your customer ID will be: " + newID);
accounts.add(new Customer(newID, accountType, currencyType, balance));
}
else if(input.equals("3")){
System.out.println("Thanks for using this bank!");
flag = false;
}
else{
System.out.println("Invalid");
}
}
}
}
My second class:
public class Customer
{
String accountType, currencyType, info;
public int customerID, balance, amount;
Scanner input = new Scanner(System.in);
public Customer(int customerID, String accountType, String currencyType, int balance)
{
this.accountType = accountType;
this.currencyType = currencyType;
this.customerID = customerID;
this.balance = balance;
this.amount = amount;
}
public Customer() {
// TODO Auto-generated constructor stub
}
public int deposit(int amount){
amount = input.nextInt();
if (amount >= 500) {
System.out.println("Invalid");
}
else{
balance = balance + amount;
}
return balance;
}
public int withdraw(int amount){
if (balance < amount) {
System.out.println("Invalid amount.");
}
else if (amount >= 500) {
System.out.println("Invalid");
}
else {
balance = balance - amount;
}
return balance;
}
public void display(ArrayList<Customer> accounts)
{
System.out.println("CustomerID:" + accounts.customerID);
System.out.println("Account Type:" + accounts.accountType);
System.out.println("Currency Type: " + accounts.currencyType);
System.out.println("Balance:" + accounts.balance);
}
public void balance(ArrayList<Customer> accounts) {
System.out.println("Balance:" + accounts.balance);
}
}
java.util.ArrayList won't have properties or methods such as customerID, accountType, currencyType and balance.
I guess your methods display() and balance() shoudn't take any arguments and should use the properties of the instance to print.
public void display()
{
System.out.println("CustomerID:" + customerID);
System.out.println("Account Type:" + accountType);
System.out.println("Currency Type: " + currencyType);
System.out.println("Balance:" + balance);
}
public void balance() {
System.out.println("Balance:" + balance);
}
Then, these lines
operation.display(accounts.get(customerID));
operation.balance(accounts.get(customerID));
should be
accounts.get(customerID).display();
accounts.get(customerID).balance();
There seems many more things to be corrected -- for example, usage of withdraw().

Removing element from TreeMap

I am creating project that allows users to create, delete etc bank accounts. I have been struggling with case 3 (remove method). I want the user to enter the account ID which will remove it from the treemap. How should the method be laid out?
package mainsample;
import java.util.*;
public class MainSample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BankProcess bankProcess = new BankProcess();
TransactionProcess transactionProcess = new TransactionProcess();
Bank bank = new Bank();
BankAccount bankAccount = new BankAccount();
int input;
int selection;
while (true) {
System.out.println("");
System.out.println("######## MENU ########");
System.out.println("[1] Create an account");
System.out.println("[2] Print all existing accounts");
System.out.println("[3] Delete an account");
System.out.println("[4] Deposit");
System.out.println("[5] Withdraw");
System.out.println("[6] Print transactions");
System.out.println("[0] Exit");
System.out.println("######################");
System.out.println("Please choose one of the following: ");
selection = scan.nextInt();
switch (selection) {
case 0:
System.out.println("Exit Successful");
System.exit(0);
break;
case 1:
System.out.println("'[1] Create an account' has been selected.");
System.out.print("Account Id: ");
int accountId = scan.nextInt();
scan.nextLine();
System.out.print("Holder Name: ");
String holderName = scan.nextLine();
System.out.print("Holder Address: ");
String holderAddress = scan.nextLine();
System.out.print("Opening Balance: ");
double openingBalance = scan.nextDouble();
System.out.print("Open Date: ");
String openDate = scan.next();
bankAccount = new BankAccount(accountId, holderName, openingBalance, holderAddress, openDate);
bank.setAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));
System.out.println("Successfully Added.");
break;
case 2:
System.out.println("'[2] Display all existing accounts' has been selected");
System.out.println("-----------------------------------------------------");
bank.getAccounts().forEach((i, b) - > System.out.println(b));
System.out.println("-----------------------------------------------------");
break;
case 3:
System.out.println("[3] Delete an account has been selected");
System.out.println("Enter the account ID: ");
int accountNo = scan.nextInt();
bank.removeAccounts(bankProcess.removeAccount(bank.getAccounts(), bankAccount));
break;
case 4:
System.out.println("[4] Deposit has been selected");
System.out.println("Enter account ID: ");
int accountNumber = scan.nextInt();
System.out.println("Enter deposit amount: ");
double depositAmount = scan.nextDouble();
transactionProcess.deposit(bankAccount, depositAmount);
System.out.println(depositAmount + " has been deposited.");
break;
case 5:
System.out.println("[5] Withdraw has been selected");
System.out.println("Enter account ID: ");
int accountNu = scan.nextInt();
System.out.println("Enter withdraw amount: ");
double withdrawAmount = scan.nextDouble();
transactionProcess.withdraw(bankAccount, withdrawAmount);
System.out.println(withdrawAmount + " has been withdrawed.");
break;
case 6:
System.out.println("[6] Print Transaction has been selected");
System.out.println("Enter account ID: ");
int accountN = scan.nextInt();
break;
default:
System.out.println("Your choice was not valid!");
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mainsample;
import java.util.*;
/**
*
* #author Khalid
*/
public class BankAccount {
private int accountId;
private String holderName;
private String holderAddress;
private String openDate;
private double currentBalance;
private List < Transaction > transactions = new ArrayList < Transaction > ();
//Provide Blank Constructor
public BankAccount() {}
//Constructor with an arguments.
public BankAccount(int accountNum, String holderNam, double currentBalance, String holderAdd, String openDate) {
this.accountId = accountNum;
this.holderName = holderNam;
this.holderAddress = holderAdd;
this.openDate = openDate;
this.currentBalance = currentBalance;
}
// Always Provide Setter and Getters
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
public String getHolderAddress() {
return holderAddress;
}
public void setHolderAddress(String holderAddress) {
this.holderAddress = holderAddress;
}
public String getOpenDate() {
return openDate;
}
public void setOpenDate(String openDate) {
this.openDate = openDate;
}
public double getCurrentBalance() {
return currentBalance;
}
public void setCurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
}
public List < Transaction > getTransactions() {
return transactions;
}
public void setTransactions(List < Transaction > transactions) {
this.transactions = transactions;
}
public void addTransaction(Transaction transaction) {
if (transactions.size() >= 6) { // test if the list has 6 or more transactions saved
transactions.remove(0); // if so, then remove the first (it's the oldest)
}
transactions.add(transaction); // the new transaction is always added, no matter how many other transactions there are already in the list
}
public String toString() {
return "\nAccount number: " + accountId + "\nHolder's name: " + holderName + "\nHolder's address: " + holderAddress + "\nOpen Date: " + openDate + "\nCurrent balance: " + currentBalance;
}
}
package mainsample;
import java.util.*;
/**
*
* #author Khalid
*/
public class Bank {
private TreeMap < Integer, BankAccount > bankAccounts = new TreeMap < Integer, BankAccount > ();
public TreeMap < Integer, BankAccount > getAccounts() {
return bankAccounts;
}
public void setAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
public BankAccount getAccount(Integer accountNumber) {
return bankAccounts.get(accountNumber);
}
public void removeAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
}
package mainsample;
import java.util.*;
/**
*
* #author Khalid
*/
public class BankProcess {
// return the Updated list of BankAccounts
public TreeMap < Integer, BankAccount > openNewAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
//Get the List of existing bank Accounts then add the new BankAccount to it.
bankAccounts.put(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
public TreeMap < Integer, BankAccount > removeAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
bankAccounts.remove(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
}
you have to get bankAccount first by accountNo you are getting from console because your removeAccount method in BankProcess expects BankAccount object for removal.
try this
case 3:
System.out.println("[3] Delete an account has been selected");
System.out.println("Enter the account ID: ");
int accountNo = scan.nextInt();
bankAccount = bank.getAccount(accountNo); // get bankAccount from account id
bank.removeAccounts(bankProcess.removeAccount(bank.getAccounts(), bankAccount));
break;

I am trying to get the average of a certain student but it adds all the the values

I am trying to get the average of a certain student but it adds all the the values. this is the output program
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
--------------------------------
Enter your choice: 1
How many Students you want to input?:
2
Student[1]Enter
Id Number: 1
First Name: Erwin
Middle Name: asdasdas
Last Name: sadasdas
Degree: asdasdas
Year Level: 1
Student[2]Enter
Id Number: 2
First Name: INK
Middle Name: asdasd
Last Name: asdas
Degree: sadas
Year Level: 3
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
--------------------------------
Enter your choice: 3
Enter Id Number: 1
----------------Student Info--------------
Id Number: 1
Name:Erwin asdasdas sadasdas
Degree and Year: asdasdas-1
The number of Subjects:
3
Name of Course: Law
Enter Grade: 3
Name of Course: Laww2
Enter Grade: 1
Name of Course: Law4
Enter Grade: 2
Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------
Enter your choice: 3
Enter Id Number: 2
----------------Student Info--------------
Id Number: 2
Name:IDK asdasd asdas
Degree and Year: sadas-3
The number of Subjects:
2
Name of Course: psych
Enter Grade: 3
Name of Course: egg
Enter Grade: 2
Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
--------------------------------
Enter your choice: 4
ENTER ID NUMBER: 1
SUM: 11.0
AVERAGE: 2.2
this is my Tester
import java.util.ArrayList;
import java.util.Scanner;
public class RecHolder {
static ArrayList<Rec> record = new ArrayList<Rec>();
static ArrayList<Grade> records = new ArrayList<Grade>();
public RecHolder() {
menu();
}
#SuppressWarnings("resource")
public static void menu() {
Scanner in = new Scanner(System.in);
int choice;
System.out.println("CMPE 325 Student Record Holder System");
System.out.println("--------------------------------");
System.out.println("1.Add Student");
System.out.println("2.View Records");
System.out.println("3.Update Students");
System.out.println("4.Get Average");
System.out.println("5.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = in.nextInt();
switch (choice)
{
case 1: record(); break;
case 2: display(); break;
case 3: update(); break;
case 4: average(); break;
case 5: break;
}
}
#SuppressWarnings("resource")
public static void record() {
Scanner in = new Scanner(System.in);
int total;
System.out.println("How many Students you want to input?: ");
total = in.nextInt();
Rec[] student = new Rec[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Rec();
System.out.printf("Student[%d]", index + 1);
System.out.println("Enter");
in.nextLine();
System.out.print("Id Number: ");
student[index].setIdNumber(in.nextLine());
System.out.print("First Name: ");
student[index].setFirstName(in.nextLine());
System.out.print("Middle Name: ");
student[index].setMiddleName(in.nextLine());
System.out.print("Last Name: ");
student[index].setLastName(in.nextLine());
System.out.print("Degree: ");
student[index].setDegree(in.nextLine());
System.out.print("Year Level: ");
student[index].setYearLevel(in.nextInt());
record.add(student[index]);
}
menu();
}
#SuppressWarnings("resource")
public static void displayall() {
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Invalid\n");
in.nextLine();
menu();
}
else
{
if(records.size() == 1){
System.out.print("-------------The Record for all Student-----------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out.print("\nId Number: " + record.get(i).getIdNumber());
System.out.print("\nName: "+ record.get(i).getFirstName() + " "+ record.get(i).getMiddleName() + " "+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "+ record.get(i).getDegree() + "-"+ record.get(i).getYearLevel()+"\n\n");
}
in.nextLine();
display();
}
else{
System.out.print("--------------The Record for all Student------------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out
.print("\nId Number: " + record.get(i).getIdNumber());
System.out.print("\nName: "+ record.get(i).getFirstName() + " "+ record.get(i).getMiddleName() + " "+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "+ record.get(i).getDegree() + "-"+ record.get(i).getYearLevel()+"\n\n");
}
// for(int loopforSubjct = 0 ; loopforSubjct < records.size(); loopforSubjct++ )
// {
// System.out.printf("\nSubject: "+ records.get(loopforSubjct).getSubject()+" Grade: "+ records.get(loopforSubjct).getGrade());
// }
in.nextLine();
}
}
display();
}
#SuppressWarnings("resource")
public static void specific() {
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
}
else{
String id = new String();
System.out.print("Enter Id Number: ");
id = in.nextLine();
if(records.size()==1){
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\n ----------------Student Exists-------------- ");
System.out.print("\nId Number: "+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"+ record.get(loopforSpcfc).getFirstName() + " "+ record.get(loopforSpcfc).getMiddleName() + " "+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "+ record.get(loopforSpcfc).getDegree() + "-"+ record.get(loopforSpcfc).getYearLevel() + "\n\n");in.nextLine();
}
else
{ in.nextLine();
System.out.print("Student Number Invalid!\n");
menu();
}
}
}
else{
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\nStudent Exists");
System.out.print("\nId Number: "+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName: "+ record.get(loopforSpcfc).getFirstName() + " "+ record.get(loopforSpcfc).getMiddleName() + " "+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "+ record.get(loopforSpcfc).getDegree() + "-"+ record.get(loopforSpcfc).getYearLevel() +"\n\n");
System.out.println();
}
}
for(int loopforSubjct = 0 ; loopforSubjct < records.size(); loopforSubjct++ )
{
System.out.printf("\nSubject: "+ records.get(loopforSubjct).getSubject()+" Grade: "+ records.get(loopforSubjct).getGrade());
}
in.nextLine();
}
}
display();
}
public static void update(){
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
}
else{
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter Id Number: ");
idnum = in.nextLine();
int total;
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (idnum.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\n ----------------Student Info-------------- ");
System.out.print("\nId Number: "+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"+ record.get(loopforSpcfc).getFirstName() + " "+ record.get(loopforSpcfc).getMiddleName() + " "+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "+ record.get(loopforSpcfc).getDegree() + "-"+ record.get(loopforSpcfc).getYearLevel() + "\n\n");in.nextLine();
}
}
for(int loop=0;loop<record.size();loop++){{
if(idnum.equals(record.get(loop).getIdNumber())){
System.out.println("The number of Sujects: ");
total = in.nextInt();
do{
Grade[] update = new Grade[total];
for(int indexupdater = 0;indexupdater<update.length;indexupdater++){
update[indexupdater] = new Grade();
in.nextLine();
System.out.print("Name of Course: ");
update[indexupdater].setSubject(in.nextLine());
System.out.print("Enter Grade: ");
update[indexupdater].setGrade(in.nextDouble());
records.add(update[indexupdater]);
}
System.out.print("Enter another subject and grade? [Y]or[N]");
String ans = in.next();
answer = ans.charAt(0);
}while(answer == 'y');
}
}
}
}
menu();
}
public static void average()
{
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
}
else{
double sum=0;
double average=0;
String ID = new String();
System.out.print("Enter An Valid Id Number: ");
for(int xx=0;xx<record.size();xx++){
if(ID.equals(record.get(xx).getIdNumber()))
{
for(int ind=0;ind<records.size();ind++)
{
sum += records.get(ind).getGrade();
}
average=sum/records.size();
System.out.println(average);
System.out.print("SUM: "+sum);
System.out.print("\nAVERAGE: "+average);
}
}
}
}
public static void display(){
Scanner input = new Scanner(System.in);
int choice;
System.out.println("--------------------------------");
System.out.println("1.View List");
System.out.println("2.View Specific Record");
System.out.println("3.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1:
displayall();
break;
case 2:
specific();
break;
case 3:
menu();
break;
}
}
public static void main(String[] args) {
new RecHolder();
}
}
This is for my Grades
public class Grade {
private String IDNumber;
private String subject;
private double grade;
private double average;
public Grade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public Grade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
for the StudntRecord
public class Rec
{
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
#Override
public String toString()
{
return ("ID Number: "+this.getIdNumber()+
"\nName: "+ this.getFirstName()+
" "+ this.getMiddleName()+
" "+ this.getLastName()+
"\nDegree and YearLevel: "+ this.getDegree() +
" - " + this.getYearLevel());
}
public Rec()
{
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Rec(String IDNum, String fName, String mName, String lName, String deg,int level )
{
this.IDNumber=IDNum;
this.firstName=fName;
this.middleName=mName;
this.lastName=lName;
this.degree=deg;
this.yearLevel=level;
}
public void setIdNumber(String IDNumber)
{
this.IDNumber = IDNumber;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public void setMiddleName(String middleName)
{
this.middleName=middleName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public void setDegree(String degree)
{
this.degree=degree;
}
public void setYearLevel(int yearLevel)
{
this.yearLevel=yearLevel;
}
public String getIdNumber()
{
return IDNumber;
}
public String getFirstName()
{
return firstName;
}
public String getMiddleName()
{
return middleName;
}
public String getLastName()
{
return lastName;
}
public String getDegree()
{
return degree;
}
public int getYearLevel()
{
return yearLevel;
}
}
Shouldn't you calculate the average AFTER everything is added into the sum?
You should calculate average outside the for loop.
for(int ind=0;ind<records.size();ind++)
{
sum += records.get(ind).getGrade();
}
average=sum/records.size();
System.out.println(average);
Average needs to be calculated after the entire for loop adds things up, Just as Prasad said before.
code is written based to complete ASSUMPTIONS since the original poster #user3145523 has not posted his complete source code when i am posting this
String ID = "fillit";
// fetch grade list
for(ArrayList gradeList2 : records.get(ID).grade)
{
double sum = 0.0;
double average = 0.0;
// cal values for all grades
for(int gradeValue : gradeList2)
{
sum = sum + gradeValue;
}
// cal average of sum
average = sum / gradeList2.count();
}
System.out.print("SUM: "+sum);
System.out.print("\nAVERAGE: "+average);
Assumptions
records is assumed to be a main ArrayList (the question is TAGGED arraylist)
the records is assumed to contain another ArrayList called grades (in the first post the user seems to have a dynamic way to allocate grade count and a simple array for grade seems unlikely )
assumed ArrayList grades is assumed to contain integer-int elements
major assumption average of grades of one student is computed . reason -> original poster said
i want that method to only calculate the a certain number.. Look the output above. it calculated all my input and get its average i need help with that
Asking user if this is fine in post (got no other option to contact)
is this fine ? ? ?
output pasted->
CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 1 How many Students you want to input?: 2 Student[1]Enter Id Number: 1 First
Name: a Middle Name: b Last Name: c Degree: 1 Year Level: 1
Student[2]Enter Id Number: 2 First Name: d Middle Name: e Last Name: f
Degree: 1 Year Level: 1 CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 3
Enter Id Number: 1
----------------Student Info-------------- Id Number: 1 Name:a b c
Degree and Year: 1-1
The number of Sujects: 2 Name of Course: aa Enter Grade: 2 Name of
Course: bb Enter Grade: 6 Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 3
Enter Id Number: 2
----------------Student Info-------------- Id Number: 2 Name:d e f
Degree and Year: 1-1
The number of Sujects: 2 Name of Course: cc Enter Grade: 5 Name of
Course: dd Enter Grade: 7 Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 4 Enter An Valid Id Number: 1 SUM: 8.0 AVERAGE: 2.0
CODE -> includes originally posted codes too (adding on user... request)
import java.util.ArrayList;
import java.util.Scanner;
public class RecHolder {
static ArrayList<Rec> record = new ArrayList<Rec>();
static ArrayList<Grade> records = new ArrayList<Grade>();
public RecHolder() {
menu();
}
#SuppressWarnings("resource")
public static void menu() {
Scanner in = new Scanner(System.in);
int choice;
System.out.println("CMPE 325 Student Record Holder System");
System.out.println("--------------------------------");
System.out.println("1.Add Student");
System.out.println("2.View Records");
System.out.println("3.Update Students");
System.out.println("4.Get Average");
System.out.println("5.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = in.nextInt();
switch (choice) {
case 1:
record();
break;
case 2:
display();
break;
case 3:
update();
break;
case 4:
average();
break;
case 5:
break;
}
}
public static void record() {
Scanner in = new Scanner(System.in);
int total;
System.out.println("How many Students you want to input?: ");
total = in.nextInt();
Rec[] student = new Rec[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Rec();
System.out.printf("Student[%d]", index + 1);
System.out.println("Enter");
in.nextLine();
System.out.print("Id Number: ");
student[index].setIdNumber(in.nextLine());
System.out.print("First Name: ");
student[index].setFirstName(in.nextLine());
System.out.print("Middle Name: ");
student[index].setMiddleName(in.nextLine());
System.out.print("Last Name: ");
student[index].setLastName(in.nextLine());
System.out.print("Degree: ");
student[index].setDegree(in.nextLine());
System.out.print("Year Level: ");
student[index].setYearLevel(in.nextInt());
record.add(student[index]);
}
menu();
}
public static void displayall() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Invalid\n");
in.nextLine();
menu();
} else {
if (records.size() == 1) {
System.out
.print("-------------The Record for all Student-----------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out.print("\nId Number: "
+ record.get(i).getIdNumber());
System.out.print("\nName: " + record.get(i).getFirstName()
+ " " + record.get(i).getMiddleName() + " "
+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(i).getDegree() + "-"
+ record.get(i).getYearLevel() + "\n\n");
}
in.nextLine();
display();
}
else {
System.out
.print("--------------The Record for all Student------------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out.print("\nId Number: "
+ record.get(i).getIdNumber());
System.out.print("\nName: " + record.get(i).getFirstName()
+ " " + record.get(i).getMiddleName() + " "
+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(i).getDegree() + "-"
+ record.get(i).getYearLevel() + "\n\n");
}
// for(int loopforSubjct = 0 ; loopforSubjct < records.size();
// loopforSubjct++ )
// {
// System.out.printf("\nSubject: "+
// records.get(loopforSubjct).getSubject()+" Grade: "+
// records.get(loopforSubjct).getGrade());
// }
in.nextLine();
}
}
display();
}
public static void specific() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
} else {
String id = new String();
System.out.print("Enter Id Number: ");
id = in.nextLine();
if (records.size() == 1) {
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out
.printf("\n ----------------Student Exists-------------- ");
System.out.print("\nId Number: "
+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"
+ record.get(loopforSpcfc).getFirstName() + " "
+ record.get(loopforSpcfc).getMiddleName()
+ " " + record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(loopforSpcfc).getDegree() + "-"
+ record.get(loopforSpcfc).getYearLevel()
+ "\n\n");
in.nextLine();
} else {
in.nextLine();
System.out.print("Student Number Invalid!\n");
menu();
}
}
}
else {
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\nStudent Exists");
System.out.print("\nId Number: "
+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName: "
+ record.get(loopforSpcfc).getFirstName() + " "
+ record.get(loopforSpcfc).getMiddleName()
+ " " + record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(loopforSpcfc).getDegree() + "-"
+ record.get(loopforSpcfc).getYearLevel()
+ "\n\n");
System.out.println();
}
}
for (int loopforSubjct = 0; loopforSubjct < records.size(); loopforSubjct++) {
System.out.printf("\nSubject: "
+ records.get(loopforSubjct).getSubject()
+ " Grade: "
+ records.get(loopforSubjct).getGrade());
}
in.nextLine();
}
}
display();
}
public static void update() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
} else {
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter Id Number: ");
idnum = in.nextLine();
int total;
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (idnum.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out
.printf("\n ----------------Student Info-------------- ");
System.out.print("\nId Number: "
+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"
+ record.get(loopforSpcfc).getFirstName() + " "
+ record.get(loopforSpcfc).getMiddleName() + " "
+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(loopforSpcfc).getDegree() + "-"
+ record.get(loopforSpcfc).getYearLevel() + "\n\n");
in.nextLine();
}
}
for (int loop = 0; loop < record.size(); loop++) {
{
if (idnum.equals(record.get(loop).getIdNumber())) {
System.out.println("The number of Sujects: ");
total = in.nextInt();
do {
Grade[] update = new Grade[total];
for (int indexupdater = 0; indexupdater < update.length; indexupdater++) {
update[indexupdater] = new Grade();
// set ID... String
update[indexupdater].setIDNumber(idnum);
in.nextLine();
System.out.print("Name of Course: ");
update[indexupdater].setSubject(in.nextLine());
System.out.print("Enter Grade: ");
update[indexupdater].setGrade(in.nextDouble());
records.add(update[indexupdater]);
}
System.out
.print("Enter another subject and grade? [Y]or[N]");
String ans = in.next();
answer = ans.charAt(0);
} while (answer == 'y');
}
}
}
}
menu();
}
public static void average() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
} else {
double sum = 0;
double average = 0;
String ID = new String();
System.out.print("Enter An Valid Id Number: ");
ID = in.nextLine();
for (Rec rec : record) {
if (rec.getIdNumber().equals(ID)) {
for (Grade grade : records) {
if (grade.getIDNumber().equals(ID)) {
// System.out.println(grade.getIDNumber());
sum = sum + grade.getGrade();
}
} // end loop-grade
average = sum / records.size();
} // end if
} // end loop-rec
System.out.print("SUM: " + sum);
System.out.print("\nAVERAGE: " + average);
}
}
public static void display() {
Scanner input = new Scanner(System.in);
int choice;
System.out.println("--------------------------------");
System.out.println("1.View List");
System.out.println("2.View Specific Record");
System.out.println("3.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1:
displayall();
break;
case 2:
specific();
break;
case 3:
menu();
break;
}
}
public static void main(String[] args) {
new RecHolder();
}
}
class Grade {
private String IDNumber;
private String subject;
private double grade;
private double average;
public Grade() {
String IDNum;
String sub;
double grad;
double ave;
}
public Grade(String IDNum, String sub, double grad, double ave) {
this.IDNumber = IDNum;
this.subject = sub;
this.grade = grad;
this.average = ave;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void setGrade(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
public String getIDNumber() {
return IDNumber;
}
public void setIDNumber(String ID) {
this.IDNumber = ID;
}
}
public class Rec {
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
#Override
public String toString() {
return ("ID Number: " + this.getIdNumber() + "\nName: "
+ this.getFirstName() + " " + this.getMiddleName() + " "
+ this.getLastName() + "\nDegree and YearLevel: "
+ this.getDegree() + " - " + this.getYearLevel());
}
public Rec() {
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Rec(String IDNum, String fName, String mName, String lName,
String deg, int level) {
this.IDNumber = IDNum;
this.firstName = fName;
this.middleName = mName;
this.lastName = lName;
this.degree = deg;
this.yearLevel = level;
}
public void setIdNumber(String IDNumber) {
this.IDNumber = IDNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setDegree(String degree) {
this.degree = degree;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
public String getIdNumber() {
return IDNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public String getDegree() {
return degree;
}
public int getYearLevel() {
return yearLevel;
}
}
You need to post the whole code so that we can understand the structure. How is the 'records' maintained and all.
With the available code, what i understand is :
if(ID.equals(record.get(xx).getIdNumber()))
This will check the condition and enter the loop.
But once entered,
for(int ind=0;ind<records.size();ind++)
{
sum += records.get(ind).getGrade();
average=sum/records.size();
}
Here, id is not considered. All the grades are summed up and average is calculated.
Your code structure may not be having link between id and the corresponding records or you are not considering the grades for the id through proper logic.
The whole code structure is required to help you further.
Maybe you can try this:
ID = in.nextLine();
for (int ind = 0; ind < records.size(); ind++) {
if (ID.equals(record.get(ind).getIdNumber())) {
sum += records.get(ind).getGrade();
}
}
System.out.print("SUM: " + sum);
average = sum / records.size();
System.out.print("\nAVERAGE: " + average);

Categories