how to code a specefic random number scheme? - java

I am learning Java. I just want to write a method that generates random numbers that comes in a specific set, like a bank credit card " xxxx - xxxx - xxxx - xxxx ". Each chunk needs to be exactly 4 digit long. anybody has any solution?
public class Main {
public static User accountHolders[] = new User[100];
public static int index = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("\t-----\tWelcome to The Bank portal\t-----");
System.out.println("\nPlease enter the number of your required action");
System.out.println("\n1) Make a Deposit");
System.out.println("2) Get balance");
System.out.println("3) Register new account");
System.out.println("0) Quit the portal");
int command = input.nextInt();
switch (command) {
case 1:
InputController.deposit();
break;
case 2:
InputController.balance();
break;
case 3:
User user = InputController.register();
accountHolders[index] = user;
index++;
break;
default:
System.out.println("Wrong input! please enter a number between 1 - 4!!!");
break;
}
}
}
}
public class Account {
private int uniID;
private int password;
private int balance;
private String cardNum;
public int getUniID() {
return uniID;
}
public int getPassword() {
return password;
}
public int getBalance() {
return balance;
}
public void makeDeposit(int amount) {
this.balance = this.balance + amount;
}
public Account(int password, int balance) {
this.password = password;
this.balance = balance;
Random rand = new Random();
this.uniID = rand.nextInt(100);
}
}
public class User {
private String name;
private Account account;
public String getName() {
return name;
}
public Account getAccount() {
return account;
}
public User(String name, Account account) {
this.name = name;
this.account = account;
}
}
public class InputController {
static Scanner input = new Scanner(System.in);
public static User register() {
System.out.print("Enter your name: ");
String name = input.next();
System.out.print("Enter your password: ");
int password = input.nextInt();
System.out.print("Please enter the amount of your initial deposit: ");
int balance = input.nextInt();
Account account = new Account(password, balance);
User user = new User(name, account);
System.out.print("Your account number is: " + account.getUniID());
return user;
}
public static void balance() {
int index = findAccount();
if (index != -1) {
System.out.print("Enter your password: ");
int password = input.nextInt();
if (Main.accountHolders[index].getAccount().getPassword() == password) {
System.out.println("Your balance is: " +
Main.accountHolders[index].getAccount().getBalance());
} else {
System.out.println("Wrong password");
}
}
}
public static void deposit() {
int index = findAccount();
if (index != -1) {
System.out.print("Enter the required amount: ");
int money = input.nextInt();
Main.accountHolders[index].getAccount().makeDeposit(money);
System.out.println("Deposit successful");
}
}
private static int findAccount() {
System.out.print("Please Enter your account number: ");
int accountNum = input.nextInt();
for (int i = 0; i < Main.index; i++) {
User user = Main.accountHolders[i];
int id = user.getAccount().getUniID();
if (id == accountNum) {
return i;
} else if (id != accountNum){
System.out.println("Account number not found");
}
}
return -1;
}
}
sorry, It's a bit long but right now this the whole thing. I want to introduce a new variable for credit card number users every time they register a new account.

Can you try below code.if you wants only one time just remove for loop.
public class RandomSetGenerator {
public static void main(String[] args) {
Random generator = new Random();
for (int i = 0; i < 10; i++) {
String string = Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000);
System.out.println("Specific set of random number generated :" + string);
}
}}

create a function which gives you the random number within a range and use it generate the same:
public class RandomSetGenerator {
public String genNumberToString(int i, int j){
Random generator = new Random();
return Integer.toString(generator.nextInt(i) + j)
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String str = genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000);
System.out.println("Specific set of random number generated :" + str);
}
}}

Related

How do I search or access an account I made in my banking system program?

I'm working on a baking system program for a school project which includes the ff. features:
Creating a new account
Balance Inquiry
Deposit
Withdraw
Close account
So far here's the code I've written:
class BankAccountAndaya {
private String accountName, address, birthday, contactNumber;
Scanner sc = new Scanner(System.in);
//default constructor
public BankAccountAndaya() {
}
public BankAccountAndaya(String accountName, String address, String birthday, String contactNumber){
this.accountName = accountName;
this.address = address;
this.birthday = birthday;
this.contactNumber = contactNumber;
}
//accessor
public String getAccountName() {
return accountName;
}
public String getAddress() {
return address;
}
public String getBirthday() {
return birthday;
}
public String getContactNumber() {
return contactNumber;
}
//mutators
public void setAccountName(String name) {
this.accountName = name;
}
public void setAddress(String address) {
this.address = address;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setContactNumber(String contactNum) {
this.contactNumber = contactNum;
}
public void getClientDetails() {
System.out.print("Enter name: ");
setAccountName(sc.next());
System.out.print("Enter address: ");
setAddress(sc.next());
System.out.print("Enter birthday (MM/DD/YY): ");
setBirthday(sc.next());
System.out.print("Enter contact number: ");
setContactNumber(sc.next());
}
}
public class SavingsAccountAndaya extends BankAccountAndaya {
private int accountNo;
private double balance, interestRate;
Random rd = new Random();
Scanner sc = new Scanner(System.in);
// default constructor
SavingsAccountAndaya() {
}
// accessors
public int getAccountNo() {
return accountNo;
}
public double getBalance() {
return balance;
}
public double getInterestRate() {
return interestRate;
}
// mutators
public void setAccountNo(int acctNo) {
this.accountNo = acctNo;
}
public void setBalance(double bal) {
this.balance = bal;
}
public void setInterestRate(double intR) {
this.interestRate = intR;
}
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
public void balanceInquiry() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.println("Client name: " + getAccountName());
System.out.println("Balance: " + getBalance());
} else {
System.out.println("Account number invalid!");
}
}
public void deposit() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to deposit: ");
double deposit = sc.nextDouble();
if (deposit >= 100) {
balance += deposit;
interestRate = 0.05 * balance;
balance += interestRate;
System.out.println("Amount deposit successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid deposit number!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void withdraw() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to withdraw: ");
double withdraw = sc.nextDouble();
double mainBal = withdraw - balance;
if (withdraw >= 100 && withdraw < balance && mainBal >= 5000) {
balance -= withdraw;
System.out.println("Amount withdrawn successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid withrawal amount!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void closeAccount() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
setAccountNo(0);
setBalance(0);
setAccountName("");
setAddress("");
setBirthday("");
setContactNumber("");
} else {
System.out.println("Invalid account number!");
}
}
}
public class ClientAndaya extends SavingsAccountAndaya {
/**
* #param args the command line arguments
*/
public static void displayMainMenu() {
System.out.println("JBank Main Menu");
System.out.println("[1] New Account");
System.out.println("[2] Balance Inquiry");
System.out.println("[3] Deposit");
System.out.println("[4] Withdraw");
System.out.println("[5] Client Profile");
System.out.println("[6] Close Account");
System.out.println("[7] Exit");
}
public static void main(String[] args) {
int i = 0;
SavingsAccountAndaya[] sa = new SavingsAccountAndaya[100];
Random rd = new Random();
Scanner sc = new Scanner(System.in);
int input;
do {
displayMainMenu();
System.out.print("Enter number: ");
input = sc.nextInt();
sa[i] = new SavingsAccountAndaya();
switch (input) {
case 1:
System.out.println("New Account: ");
sa[i].getClientDetails();
System.out.print("Enter amount to deposit: ");
double inDepo = sc.nextDouble();
if (inDepo < 5000) {
System.out.println("Invalid initial deposit amount!");
System.out.println("Amount must be greater than 5000 PHP");
System.out.print("Enter amount to deposit: ");
inDepo = sc.nextDouble();
}
sa[i].setBalance(inDepo);
// generate account number
int ranNo = rd.nextInt(9999);
sa[i].setAccountNo(ranNo);
System.out.println("Account number: " + sa[i].getAccountNo());
i++;
break;
case 2:
System.out.println("Balance Inquiry: ");
sa[i].balanceInquiry();
break;
case 3:
System.out.println("Deposit: ");
sa[i].deposit();
break;
case 4:
System.out.println("Withdraw: ");
sa[i].withdraw();
break;
case 5:
System.out.println("Client Profile: ");
System.out.println("Account number: " + sa[i].getAccountNo());
System.out.println("Accoutn Name: " + sa[i].getAccountName());
System.out.println("Address: " + sa[i].getAddress());
System.out.println("Birthday: " + sa[i].getBirthday());
System.out.println("Contact Number: " + sa[i].getContactNumber());
System.out.println("Balance: " + sa[i].getBalance());
break;
case 6:
System.out.println("Close Account: ");
sa[i].closeAccount();
break;
case 7:
break;
default:
System.out.println("Invalid chosen number!");
}
} while (input < 6 && input > 0);
}
}
I can't seem to access or search for an account I've created. Whenever I input the account number, it always results to invalid account number even though I've already created an account that has that account number. I think the problem lies with the validateAcctNumber method:
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
It was also mentioned in the instructions to use exception to validate inputs.
How can I solve this problem? Thank you for your help.

Create user with list of data

The program should contain the customers plus a list of the calories and the distance during the week.
My question is, how can I put together the customer's name and the distance?
public class TestCustomer {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> customersNames = new ArrayList<String>();
char userInput = ' ';
System.out.println("A to show all");
userInput = scan.next().charAt(0);
if(userInput == 'A') {
System.out.println("All results ");
for(int i = 0; i < customersNames.size(); i++) {
System.out.println(customersNames.get(i));
}
}
}
And here's my Customer class
public class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double distance) {
this.name = name;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return distance;
}
}
This uses a list of customers instead of customernames.
I put the Customer class as static in the testclass for brevity(keep everything in one file). Better to have it seperate as you do.
Also I did not want to change the whole design or do a complete rewrite - it is your design. So this is only making it work, fixing the behavior to the one required.
Eg with having the customers in HashMap that is indexed by name one could retrieve a dataset more elegantly in O(1). But thats maybe another improvement.
This only has the list. So for simplicity I added an equals, that makes users equal if they have the same name.
I create a new User that can be searched in the list. If not found I add this user with the given input to the list.
If found I search for existing the user in the list with indexOf and retrieve that existing user. I do it in one step.
import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;
public class TestCustomer {
public static class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double calories, double distance) {
this.name = name;
this.calories = calories;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return this.distance;
}
#Override
public int hashCode() {
int hash = 5;
hash = 71 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return Objects.equals(this.name, ((Customer)obj).name);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Customer> customers = new ArrayList<>();
char userInput = ' ';
while (userInput != 'q') {
System.out.println("Press 'a' to show all customers or press 's' to search for customer ");
userInput = scan.next().charAt(0);
userInput = Character.toUpperCase(userInput);
if (userInput == 'A') {
System.out.println("Here's the list of all customers: ");
for (int i = 0; i < customers.size(); i++) {
System.out.println(customers.get(i).getName());
}
// here I should show the list of all customers and their data
} else if (userInput == 'S') {
System.out.println("You selected to search for a customer");
createCustomer(customers);
}
}
}
public static ArrayList<Customer> createCustomer(ArrayList<Customer> customers) {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter customer's first name: ");
String fName = scan2.next();
System.out.println("Enter customer's last name: ");
String lName = scan2.next();
String fullName = fName + " " + lName;
Customer newCustomer = new Customer(fullName,0,0);
if (customers.contains(newCustomer)) {
newCustomer=customers.get(customers.indexOf(newCustomer));
System.out.println("Customer already on the list. Here's the information: ");
System.out.println(fullName + " " + newCustomer.distance + " " + newCustomer.calories );
} else{
System.out.println("Customer not found. Would you like to create a new customer? y/n ");
char createUserPrompt = scan2.next().charAt(0);
if (createUserPrompt == 'y') {
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for (String daysOfWeek1 : daysOfWeek) {
System.out.println("Enter calories consumed on " + daysOfWeek1);
newCustomer.calories = scan2.nextDouble();
System.out.println("Enter distance walked on " + daysOfWeek1);
newCustomer.distance = scan2.nextDouble();
}
customers.add(newCustomer);
} else if (createUserPrompt == 'n') {
System.out.println("User will not be added.");
}
}
return customers;
}
}
sample run:
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer not found. Would you like to create a new customer? y/n
y
Enter calories consumed on Monday
5
Enter distance walked on Monday
5
Enter calories consumed on Tuesday
5
Enter distance walked on Tuesday
5
Enter calories consumed on Wednesday
5
Enter distance walked on Wednesday
5
Enter calories consumed on Thursday
5
Enter distance walked on Thursday
5
Enter calories consumed on Friday
5
Enter distance walked on Friday
5
Enter calories consumed on Saturday
5
Enter distance walked on Saturday
5
Enter calories consumed on Sunday
5
Enter distance walked on Sunday
5
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
kai last
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer already on the list. Here's the information:
kai last 5.0 5.0
Press 'a' to show all customers or press 's' to search for customer
With some modifications to your Customer class in which the calories and distance will be stored ad an array for each day,
An ArrayList<Customer> will be used to store the list of customers.
Possible solution:
import java.util.*;
public class Main {
private static Scanner scan;
private static ArrayList<Customer> customers;
public static Customer customerExists(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getName().equals(customerName)) {
return customers.get(i);
}
}
return null;
}
public static void addCustomer() {
System.out.println(">> Add Customer <<\n");
System.out.print("Enter customer's first name: ");
String fName = scan.nextLine();
System.out.print("Enter customer's last name: ");
String lName = scan.nextLine();
String fullName = fName + " " + lName;
Customer existingCustomer = customerExists(fullName);
if (existingCustomer != null) {
System.out.println("\nCustomer already on the list. Here's the information: ");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(existingCustomer.getName() + "\t" + Arrays.toString(existingCustomer.getCalories()) + "\t" + Arrays.toString(existingCustomer.getDistance()));
return;
}
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
double calories[] = new double[daysOfWeek.length];
double distance[] = new double[daysOfWeek.length];
for (int j = 0; j < daysOfWeek.length; j++) {
System.out.print("Enter calories consumed on " + daysOfWeek[j] + ": ");
calories[j] = scan.nextDouble();
System.out.print("Enter distance walked on " + daysOfWeek[j] + ": ");
distance[j] = scan.nextDouble();
}
Customer customer = new Customer(fullName, calories, distance);
customers.add(customer);
System.out.println("\nCustomer added successfully!\n");
}
public static void showCustomers() {
System.out.println(">> All Customers <<\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
for (int i = 0; i < customers.size(); i++) {
System.out.println(i+1 + "\t" + customers.get(i).getName() + "\t" + Arrays.toString(customers.get(i).getCalories()) + "\t\t\t" + Arrays.toString(customers.get(i).getDistance()));
}
System.out.println("\n");
}
public static void searchCustomers() {
System.out.println(">> Search for a Customer <<\n");
System.out.print("Enter customer's full name: ");
String fullName = scan.nextLine();
Customer customer = customerExists(fullName);
System.out.println(fullName);
if (customer == null) {
System.out.println("\nNo such customer exists.\n");
return;
}
System.out.println("\nCustomer information:\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(customer.getName() + "\t" + Arrays.toString(customer.getCalories()) + "\t" + Arrays.toString(customer.getDistance()) + "\n");
}
public static void main(String[] args) {
boolean cont = true;
int option = -1;
scan = new Scanner(System.in);
customers = new ArrayList<>();
do {
System.out.println("=== Select an Option ===");
System.out.println("1. Add a customer");
System.out.println("2. Show all customers");
System.out.println("3. Search for customer");
System.out.println("0. Exit");
System.out.print("\n > ");
try {
option = Integer.parseInt(scan.nextLine());
System.out.println("\n");
switch(option) {
case 1:
addCustomer();
break;
case 2:
showCustomers();
break;
case 3:
searchCustomers();
break;
case 0:
System.out.println("Good Bye!");
cont = false;
break;
default:
System.err.println("'" + option + "' is not a valid option. Please try again.\n");
break;
}
} catch (NumberFormatException e) {
System.err.println("Invalid option selected.\n");
}
} while (cont == true);
}
}

Bank Account Java Program

I am creating a bank account program for my java class that is suppose to manage up to 5 different bank accounts. The program has to allow the creation of a new account, which I have done, allow deposit and withdraw, which is also done, the 2 parts I cannot get to work are 1: the bank can only have up to 5 accounts, so if a 6th is trying to be created, a message comes up saying that 5 are already created, and 2: one of the options has to print out all the account balances of current accounts in the bank.
This is my code as of now:
import java.util.Scanner;
public class Bankapp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print account balance");
System.out.println("5) Quit");
System.out.println();
System.out.print("Enter choice [1-5]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1:
System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
case 5:
System.out.println("Here are the balances " + "for each account:");
case 6:
System.exit(0);
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts = 5; // the number of bank accounts at this bank
// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[5];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
}
public int getAccountNum(){
return accountNum;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
}
}
}
}//end of class
The program runs fine, I just need to add these two options, and cannot get them to work properly, how would I go about doing this? Also, options 3 and 4 should not work if no accounts have been created yet. Thanks in advance.
UPDATE: this is what I tried, I keep getting a this method must return type int error.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
}
UPDATE 2: I added a return statement, now when it runs it will open accounts up to number 5, but for every account after number 5 it just says the account number is 5 again instead of not opening an account.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
return numOfAccounts;
}
Its pretty simple. Create a list of size 5 and add the account into that list when user is created one. Before adding just make a check whether list size <= 5. If it is true, go ahead and add the account, otherwise throw an error
For option 2, just iterate through the list and display the results
1; in the openNewBank account method; before creating the new Bank account and increasing the count by 1; check if the number of account is already at 5 or higher and if it is dont create the account and dont increase the count.
2: Loop through the number of account variable and print.
I added password system to it. and nice looking account num.
Code :
import java.io.*;
import java.util.Random;
public class Computer_Bank_of_India {
public static int NewRandom(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String args[])throws IOException, InterruptedException {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
Bank myBank = new Bank();
int Option = 1, Account_Number, Account_Password, atempts = 0, Pass;
String Name;
double Balance, Money;
System.out.println("Please wait, the system is starting...");
while(Option !=5) {
Thread.sleep(4000);
System.out.println("1) Open a new bank account");
Thread.sleep(250);
System.out.println("2) Deposit to a bank account");
Thread.sleep(250);
System.out.println("3) Withdraw to bank account");
Thread.sleep(250);
System.out.println("4) Print the detailed account information including last transactions");
Thread.sleep(250);
System.out.println("5) Quit");
System.out.println();
System.out.print(" Enter Option [1-5]: ");
Option = Integer.parseInt(br.readLine());
switch(Option) {
case 1 : System.out.println("Enter a customer name :");
Name = br.readLine();
System.out.println("Enter a opening balance :");
Balance = Double.parseDouble(br.readLine());
Thread.sleep(250);
System.out.println("Creating your account....");
Thread.sleep(500);
int[] arrDetails= myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[1]);
break;
case 2 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Deposit(Account_Number, Account_Password, Money);
break;
case 3 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Withdraw(Account_Number, Account_Password, Money);
break;
case 4 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
myBank.Transactions(Account_Number, Account_Password);
break;
case 5 : System.out.println("Please Enter your password :");
Pass = Integer.parseInt(br.readLine());
if(Pass == myBank.Password) {
System.out.println(" System shutting down.....");
Option = 5;
break;
}
else {
Thread.sleep(250);
System.out.println("You have enter a wrong password. Please try again");
Option = 0;
}
default: System.out.println("Invalid option. Please try again.");
}
}
}
static class Bank {
private int Password=2684;
private BankAccount[] accounts;
private int numOfAccounts;
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
public int [] AddNewAccount(String Name, Double Balance) {
BankAccount b = new BankAccount(Name, Balance);
accounts[numOfAccounts] = b;
numOfAccounts++;
int Acc = b.getAccountNum()[0];
int Pass = b.getAccountNum()[1];
int[]details = {Acc, Pass};
return details;
}
public void Withdraw(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].withdraw(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Deposit(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].deposit(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Transactions(int Account_Number, int pass) {
for(int i = 0;i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a ) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(" Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
}
static class BankAccount{
private int User_Password;
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private String[] transactionsSummary;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return " Account number: " + accountNum + "\n Customer Name: " + customerName + "\n Balance:" + balance +"\n";
}
public String getTransactionInfo(int n) {
String transaction = transactionsSummary[n];
return transaction;
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
User_Password = NewRandom(1000, 9999);
accountNum = NewRandom(800000000, 999999999);
transactions = new double[100];
transactionsSummary = new String[100];
transactions[0] = balance;
transactionsSummary[0] = "A balance of : Rs" + Double.toString(balance) + " was deposited.";
numOfTransactions = 1;
}
public int [] getAccountNum(){
int account = accountNum;
int Pass = User_Password;
int [] details = {account, Pass};
return details;
}
public int getNumberOfTransactions() {
return numOfTransactions;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was deposited.";
numOfTransactions++;
System.out.println(" Amount deposited successfully");
}
}
public void withdraw(double amount) {
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else {
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was withdrawn.";
numOfTransactions++;
System.out.println(" Amount Withdrawn successfully");
}
}
}
}
}

Getting a Null Pointer Exception and not sure how to fix it [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am creating a tester class for a simple input database program. I do not have to store information nor delete anything, but there are two arrays in my the class I am running my tester class for.
This is my tester class:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
Policy insurance = new Policy();
insurance.setCustomerLast(null);
insurance.setCustomerFirst(null);
insurance.setPolicyNumber();
insurance.setAge();
insurance.setAccidentNumber();
insurance.setPremiumDueDate(00,00,0000);
//insurance.toString();
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(null);
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.getPolicyNumber();
System.out.println("Customer's Policy Number is: " + keyboard.nextInt());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.getCustomerLast();
System.out.println("Customer's Last Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.getCustomerFirst();
System.out.println("Customer's First Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.getAge();
System.out.println("Customer's Age is: " + keyboard.nextInt());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.getAccidentNumber();
System.out.println("Customer's Amount of Accidents is: " + keyboard.nextInt());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.getPremiumDueDate();
System.out.println("Customer's Next Due Date is: " + keyboard.nextInt());
insurance.toString();
showMenuOptions();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the Null Pointer Error:
Exception in thread "main" java.lang.NullPointerException
at Asst_3.newPolicy(Asst_3.java:55)
at Asst_3.intiateMenuSelection(Asst_3.java:40)
at Asst_3.main(Asst_3.java:35)
This is the class I'm making my tester for:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
Thank you everyone, your amazing!
Here's my edited code:
The Tester
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the class being tested:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(int policyNumber){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(int accidentNumber){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
But now I have a new error after executing the program:
Welcome to Drive-Rite Insurance Company
Choose a menu option:
(1) Create New Policies
(2) Search by age
(3) Search by due date
(4) Exit
Input Option Number ---> Exception in thread "main" java.lang.NullPointerException
at Asst_3.main(Asst_3.java:23)
Here's an updated version with that NPE fixed:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
this.keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("----------------------------------------");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
The errors are I'm having issues with they keyboard variables.
null pointer occurring in
private static void newPolicy(Policy insurance)
this method. For these lines
insurance.getPolicyNumber();
insurance.get....();
insurance.get....();
because the reference/object insurance coming as a parameter from where its being called . in you case you are passing null to the method
newPolicy(null); //try to pass a reference of Policy like 'newPolicy(new Policy())' .
You declare keybord twice.
remove the Scanner from this line:
Scanner keyboard = new Scanner(System.in);
So you have:
keyboard = new Scanner(System.in);
You're shadowing you variables, that is, you've declared keyboard as a class variable
public class Asst_3 {
private static Scanner keyboard;
But in the main, you've re-declared it as a local variable...
Scanner keyboard = new Scanner(System.in);
Which means that the class variable is still null when you call newPolicy.
Start by removing the re-declaration...
//Scanner keyboard = new Scanner(System.in);
keyboard = new Scanner(System.in);
Which will lead you smack bang into you next NullPointerException in newPolicy
insurance.getPolicyNumber();
Caused by the fact that you call the method passing it a null value...
newPolicy(null);
I'll leave you to fix that ;)
Hint: newPolicy should take no parameters and should return an new instance of Policy which can then manipulated by the other methods ;)
The insurance that you are passing to newPolicy is null
case 1: newPolicy(null);
hence
insurance.getPolicyNumber();
will throw a NPE

Updating Student Information (Runtime)

This is my code for STUDENT RECORD SYSTEM. I think it is on its 80% of completion. The problem here is that when i have many students and i update a specific student(subj & grade) the updated element is not being saved on that specific student. And when I display all of the results the updated values are given to other student. Please help me out with this issue. And btw this code has 2 classes Student and StudentGrade. I hope you'll help me fix this. Thanks in advance. :) and Advance Happy New Year!
public class Student
{
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student()
{
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Student(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 String getIdNumber()
{
return IDNumber;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName()
{
return firstName;
}
public void setMiddleName(String middleName)
{
this.middleName=middleName;
}
public String getMiddleName()
{
return middleName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public String getLastName()
{
return lastName;
}
public void setDegree(String degree)
{
this.degree=degree;
}
public String getDegree()
{
return degree;
}
public void setYearLevel(int yearLevel)
{
this.yearLevel=yearLevel;
}
public int getYearLevel()
{
return yearLevel;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(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 class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(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;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class test2 {
static ArrayList<Student> studentList = new ArrayList<Student>();
static ArrayList<StudentGrade> studentLists = new ArrayList<StudentGrade>();
public static void main(String[] args)
{
menu();
}
public static void menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("*********STUDENT RECORD SYSTEM*********\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1)
{
add();
}
else if (choice == 2)
{
displayAll();
}
else if (choice == 3)
{
displaySpecific();
}
else if (choice == 4)
{
update();
}
else if (choice == 5)
{
average();
}
else if( choice == 6)
{
System.exit(0);
}
else
menu();
}
public static void add()
{
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("NUMBER OF STUDENTS YOU WANT TO INPUT: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("**********STUDENT INFORMATION**********\n\n");
System.out.println("PRESS 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());
studentList.add(student[index]);
}
System.out.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
/* // SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
} */
menu();
}
public static void displayAll() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY lageeeee!!! \nPLEASE INPUT FIRST\n\n");
in.nextLine();
}
else
{
if(studentLists.size() == 0){
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()/* +"\nGrade: "
+ studentLists.get(i).getGrade() */+"\n\n");
}
in.nextLine();
}
else{
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++)
{
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()+"\n\n");
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void displaySpecific() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY oe!!! KALAGOT!\nPLEASE INPUT FIRST\n");
in.nextLine();
}
else
{
String id = new String();
/* in.nextLine(); */
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
if(studentLists.size()==0)
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + /* "\nGrade: "
+ studentLists.get(j).getGrade()+ */"\n\n");
System.out.println();
in.nextLine();
}
/* else
{
System.out.print("STUDENT DOES NOT EXIST IN THIS WORLD!");
in.nextLine();
} */
}
}
else
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() +"\n\n");
System.out.println();
}
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();
int total;
for(int x=0;x<studentList.size();x++)
{
if(idnum.equals(studentList.get(x).getIdNumber()))
{
System.out.println("NUMBER OF SUJECTS YOU WANT TO INPUT: ");
total = in.nextInt();
do
{
StudentGrade[] update = new StudentGrade[total];
for(int y = 0;y<update.length;y++)
{
update[y] = new StudentGrade();
in.nextLine();
System.out.print("ENTER SUBJECT: ");
update[y].setSubject(in.nextLine());
System.out.print("ENTER GRADE: ");
update[y].setGrade(in.nextDouble());
studentLists.add(update[y]);
}
System.out.print("Enter another subject and grade? [y/n]");
String ans = in.next();
answer = ans.charAt(0);
}while(answer == 'y');
}
menu();
}
}
public static void average()
{
Scanner in = new Scanner(System.in);
double sum=0;
double average=0;
String ID = new String();
System.out.print("ENTER ID NUMBER: ");
ID = in.nextLine();
for(int xx=0;xx<studentList.size();xx++)
{
if(ID.equals(studentList.get(xx).getIdNumber()))
{
for(int ind=0;ind<studentLists.size();ind++)
{
sum += studentLists.get(ind).getGrade();
average=sum/studentLists.size();
}
System.out.print("ID NUMBER:"+studentList.get(xx).getIdNumber()+"\nNAME: "
+studentList.get(xx).getFirstName()+" "
+studentList.get(xx).getMiddleName()+" "
+studentList.get(xx).getLastName());
System.out.print("\nAVERAGE: "+average+"\n");
in.nextLine();
}
}
menu();
}
}
First of all I would change studentList to Map to be able to get the student by id directly and not to search for the matching student every time.
The access to the collections of all students is then like this:
for(Map.Entry<String, Student> entry : studentList.entrySet()){
String id = entry.getKey();
Student student = entry.getValue();
// ...
}
A a second step you should check your update method. I see, that you a searching for the student, but you don't updating this object. You are adding a new one at the end of the loop with studentList.add().
You have store the matching Student into the local variable and just modify this without modifying the collection of students.
You have two reader statements in update function
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();//1
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();//2
I think there should be only one as your just reading the id number and as #Vlad said your adding a new element to the array list rather than modifying the existing data .
also for your code you can use
arrayList.set(index i,String replaceElement);// this will help you replace the value at a particular index
it is better to use HashMap instead of array list so when you put an existing element into
a map the value is overwritten.
static Map <String,Student> studentList = new HashMap<String,Student>();
static Map<String, List<StudentGrade>> studentLists = new HashMap<String, List<StudentGrade>>();
Here the key will be the student idNumber

Categories

Resources