I am creating in the console a program that adds new students but i wish to check if the max capacity of students is reached or not.
I am learning Java on my own so sorry if my code is not as it should be.
I would appreciate your feedback if you have suggestions.
Main
boolean abort = false;
boolean unlocked = false;
//Student[] students = new Student[School.MAX_studentEntered];
ArrayList<Student> students= new ArrayList<>();
Scanner option = new Scanner(System.in);
while (!abort){ //for as long as the value is not abort the loop will run
System.out.println("Unlock Admin(1) New Student(2) Show Students(3) Statistics (4) ");
System.out.print("Input: ");
int input = option.nextInt();
switch (input){
case 0:{
abort = true;
break;
}
case 1:{
System.out.println("Admin");
unlocked = true;
break;
}
//problem is case 2
case 2: {
System.out.println("Create a student");
int time = 0;
while (time<=School.MAX_studentEntered) {
Scanner st = new Scanner(System.in);
System.out.print("Name: ");
String name = st.nextLine();
System.out.print("Age: ");
int age = st.nextInt();
Student student = new Student();
student.setName(name);
student.setAge(age);
students.add(student);
time++;
if(unlocked){
System.out.print("Create another student? (yes/no): ");
Scanner ans= new Scanner(System.in);
String answer = ans.nextLine();
if (!answer.equals("yes")) {
break;
}
else {
if(time>School.MAX_studentEntered){
System.out.println("You have reached the max capacity!");
break;
}
else {
continue;
}
}
}
if(time>School.MAX_studentEntered){
System.out.println("You have reached the max capacity!");
break;
}
else {
break;
}
}
break;
}
Class Student
public class Student {
String name;
int age;
public Student(){
School.studentEntered++;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){ //void - save the value
this.age = age;
}
public String getName(){ //return - show the value
return name;
}
public int getAge(){
return age;
}
}
School Class
public class School {
static int studentEntered = 0;
static final int MAX_studentEntered=3;
public School(){
// it is automaticlly created when the class is created
// it does not need a void or return
studentEntered++;
}
}
I expect the program to stop adding new students in the arrayList if the capacity (MAX_studentEntered) is reached and to print an error after the break
Related
public class Attraction {
String description;
private String contactDetails;
private String guide;
private String rating;
private final double noTicketsSold = 0;
private int maxGroupSize;
private int amountActivities;
private double ticketCost;
private int uniqueID;
private static int count;
private char chosen;
private String[] storedActivities;
private static int id_counter = 0;
private final int MAX_NUM_ATTRACTIONS = 5;
private static int[] attractions;
public Attraction(int MAX_NUM_ATTRACTIONS) {
id_counter++;
attractions = new int[MAX_NUM_ATTRACTIONS];
count = 0;
}
public int getUniqueID() {
return this.uniqueID;
}
public void recordAttraction() {
if (count == attractions.length) {
System.out.println("Attractions are full");
return;
}
if (count < attractions.length) {
attractions[count] =
count++;
}
}
public Attraction(char chosen, String description, double ticketCost, int maxGroupSize, String contactDetails,
int amountActivities, String[] storedActivities) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.maxGroupSize = maxGroupSize;
this.contactDetails = contactDetails;
this.amountActivities = amountActivities;
this.storedActivities = storedActivities;
}
public Attraction(char chosen, String description, double ticketCost, String guide, String rating) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.guide = guide;
this.rating = rating;
}
public void displayAllDetails() {
System.out.printf("\nID : %d%n", getUniqueID());
System.out.printf("Description : %s%n", description);
System.out.printf("Ticket cost : $%.2f%n", ticketCost);
System.out.printf("Tickets sold : %.0f%n", noTicketsSold);
if (chosen == 'y') {
System.out.println("Activity :");
int i = 0;
while (amountActivities > i) {
System.out.println(" : " + storedActivities[i]);
i++;
}
System.out.printf("Max Attendees : %d%n", maxGroupSize);
System.out.printf("Agency : %s%n", contactDetails);
}
if (chosen == 'n') {
System.out.printf("Instruction guide : %s%n", guide);
System.out.printf("Difficulty : %s%n", rating);
}
}
}
import java.util.Scanner;
public class StageA {
private static final Scanner sc = new Scanner(System.in);
private Attraction attractions = null;
public static void main(String[] args) {
StageA a = new StageA();
a.runMenu();
}
private void runMenu() {
char selection;
do {
displayMenu();
selection = sc.nextLine().toLowerCase().charAt(0);
processSelection(selection);
} while (selection != 'x');
}
private void displayMenu() {
System.out.println("\n **** Ozzey Attraction Menu ****");
System.out.println("A : Add New Attraction");
System.out.println("B : View Attraction");
System.out.println("C : List All Attractions");
System.out.println("D : Sell Ticket");
System.out.println("E : Refund Ticket");
System.out.println("F : Remove Attraction");
System.out.println("X : Exit\n\n");
System.out.printf("Enter selection : ");
}
private void createAttraction() {
String description;
double ticketCost;
char chosen;
int maxGroupSize;
String contactDetails;
int amountActivities;
System.out.print("\nEnter attraction description : ");
description = sc.nextLine();
System.out.print("Enter cost of a Ticket : ");
ticketCost = Double.parseDouble(sc.nextLine());
System.out.println("Is this a supervised tour ? [Y/N] :");
chosen = sc.nextLine().toLowerCase().charAt(0);
switch (chosen) {
case 'y':
System.out.println("What is maximum permitted tour group size?");
maxGroupSize = Integer.parseInt(sc.nextLine());
System.out.println("Enter the agency contact details: ");
contactDetails = sc.nextLine();
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
while (amountActivities < 1) {
System.out.println("Please enter valid number of activities great than zero");
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
}
String[] storedActivities = new String[amountActivities];
int counter = 0;
while (amountActivities > counter) {
System.out.printf("Please enter activity #%d: ", counter);
storedActivities[counter] = sc.nextLine();
counter++;
}
attractions = new Attraction(chosen, description, ticketCost, maxGroupSize, contactDetails,
amountActivities, storedActivities);
break;
case 'n':
String guide;
String rating;
System.out.printf("Enter the instruction guide:\n");
guide = sc.nextLine();
System.out.printf("Enter the difficulty rating:\n");
rating = sc.nextLine();
attractions = new Attraction(chosen, description, ticketCost, guide, rating);
break;
default:
System.out.print("Please Enter valid answer ");
System.out.println("Is this a supervised tour ? [Y/N] :");
}
}
private void processSelection(char selection) {
switch (selection) {
case 'a':
attractions.recordAttraction();
createAttraction();
break;
case 'b':
System.out.printf("b");
break;
case 'c':
System.out.printf("c");
break;
case 'd':
System.out.printf("d");
break;
case 'e':
System.out.printf("e");
break;
case 'f':
System.out.printf("f");
break;
case 'x':
System.out.println("Good Bye!");
break;
default:
System.out.println("Invalid input, try again\n");
}
}
Hi all i stuck a part of my project for school i have to create a single array in my Attraction class called int[] attractions that can have a max of 5 stored createAttraction() from my stageA class.
When they choose 'a' in my switch statement this were i add createAttraction(); when user has created five attraction in will then tell the user its full and no more can be added. i tried a couple of things but i stuck any help wont be appreciated.
Note: this is the way project has to be setup.
Here are few things you should change in your code :
Change the constructor in attractions class, since you have already set final variable as 5 and if it is fixed, you do not need constructor with parameter: MAX_NUM_ATTRACTIONS
You need to initialise attraction object in StageA class :
private Attraction attractions = null; => private Attraction attractions = new Attraction()
Decide when you want to increment counter variable, when you dorecordAttraction or actually creating one and count should be checked greater or equal to attractions length/ MAX_NUM_ATTRACTIONS
return a value from method record Attraction to decide if you have to proceed with createAttraction or not
I am needing to store 3 different bits of data into a linked list. the first is a name, which i have working, then i need to store the employee number and their occupation. I can't find anything about linking a node to a set of data. any help would be greatly appreciated.
This is the code that runs, TeamMemberTest:
package teammember;
import java.util.*;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String args[]) {
/* Linked List Declaration */
LinkedList<String> linkedlist = new LinkedList<String>();
Scanner input = new Scanner(System.in);
boolean mainloop = true;
String name;
int employeeNo;
String position;
int choice;
while(true){
System.out.println("Menu");
System.out.print("1. add project \n");
System.out.print("2. display project \n");
System.out.print("3. remove project \n");
System.out.print("4. display all projects \n");
System.out.print("\nEnter your option: ");
choice = input.nextInt();
switch(choice){
case 1:
/*add(String Element) is used for adding
* the elements to the linked list*/
name = Input.getString("name: ");
employeeNo = Input.getInteger("Enter employee number: ");
position = Input.getString("Enter employee position: ");
linkedlist.add(name);
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
break;
case 2:
name = Input.getString("name: ");
if(linkedlist.contains(name)){
System.out.println("LinkedList does contain " + name);
}
break;
case 3:
name = Input.getString("name: ");
linkedlist.remove(name);
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
break;
case 4:
System.out.println("Linked List Content: " +linkedlist);
break;
default :
System.out.println("This is not a valid option try again.");
break;
}
}
}
}
this code below is TeamMember.java:
package teammember;
public class TeamMember {
//variables
private String name;
private int employeeNo;
private String position;
//the default constant
public TeamMember(){
name = " ";
employeeNo = 0;
position = " ";
}
//overload the constructor
public TeamMember(String name, int employeeNo, String position){
this.name = name;
this.employeeNo = employeeNo;
this.position = position;
}
//the methods
public void setName(String name){
this.name = name;
}
public void setemployeeNo(int employeeNo){
this.employeeNo = employeeNo;
}
public void setPosition(String position){
this.position = position;
}
public String getName(){
return name;
}
public int getemployeeNo(){
return employeeNo;
}
public String getPosition(){
return position;
}
}
and this is the input code:
package teammember;
import java.io.*;
public class Input{
private static BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
public static Character getCharacter(String prompt){
Character value;
System.out.print(prompt);
try{
value=Input.input.readLine().charAt(0);
}
catch(Exception error){
// error condition
value=null;
}
return value;
}
public static Double getDouble(String prompt){
Double value;
System.out.print(prompt);
try{
value=Double.parseDouble(Input.input.readLine());
}
catch(Exception error){
// error condition
throw new NumberFormatException();
}
return value;
}
public static Integer getInteger(String prompt){
Integer value;
System.out.print(prompt);
try{
value=Integer.parseInt(Input.input.readLine());
}
catch(Exception error){
// error condition
throw new NumberFormatException();
}
return value;
}
public static String getString(String prompt){
String string;
System.out.print(prompt);
try{
string=Input.input.readLine();
}
catch(Exception error){
// error condition
string=null;
}
return string;
}
}
Instead of creating a LinkedList of String, you need to create a LinkedList of TeamMember as follows:
LinkedList<TeamMember> linkedlist = new LinkedList<TeamMember>();
Then you need to change the cases accordingly e.g.
choice = input.nextInt();
boolean found;
switch (choice) {
case 1:
name = Input.getString("name: ");
employeeNo = Input.getInteger("Enter employee number: ");
position = Input.getString("Enter employee position: ");
linkedlist.add(new TeamMember(name, employeeNo, position));
break;
case 2:
found = false;
name = Input.getString("name: ");
for (TeamMember teamMember : linkedlist) {
if (teamMember.getName().equalsIgnoreCase(name)) {
System.out.println("Name: " + teamMember.getName() + "Employee No.: "
+ teamMember.getemployeeNo() + "Position: " + teamMember.getPosition());
found = true;
break;
}
}
if (!found) {
System.out.println("The team member was not found.");
}
break;
case 3:
found = false;
name = Input.getString("name: ");
for (TeamMember teamMember : linkedlist) {
if (teamMember.getName().equalsIgnoreCase(name)) {
linkedlist.remove(teamMember);
found = true;
break;
}
}
if (found) {
System.out.println("LinkedList after deletion of " + name + "'s record" + ": " + linkedlist);
} else {
System.out.println("The team member was not found.");
}
break;
case 4:
System.out.println("Linked List Content: " + linkedlist);
break;
default:
System.out.println("This is not a valid option try again.");
break;
}
Make sure to add a toString() method in the class, TeamMember so that you can simply do like System.out.println(an-object-of-TeamMember);. Your IDE can generate the toString() method on the click of a button. Given below is an autogenerated toString() method for your class by eclipse IDE:
#Override
public String toString() {
return "TeamMember [name=" + name + ", employeeNo=" + employeeNo + ", position=" + position + "]";
}
Check this to learn more about toString().
I am trying to search an arraylist of objects for an ID code, but I am stuck.
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1:
addTransaction(argList);
break;
case 2:
;// Search Transaction
break;
case 3:
;// Filter Withdraws and Deposits
break;
case 4:
;// Display transactions
break;
case 5:
System.out.println("End");
break;
default:
System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription) ); }
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.argId.get(i).contains(searchId)){
System.out.println("Yes");
}
}
}
}
My second file contains this
public class Transaction {
int id;
char type;
double amount;
String description;
public Transaction(int argId, double argAmount,char argType, String
argDescription){
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public void getId(int id){
}
public void getAmount(double amount){
}
public void getType(char type){
}
public void getDescription(String description){
}
}
And i get the error message: argId cannot be resolved or is not a field on line 58. I think my error is that argId is not part of the ArrayList, and i need to find the right tern to search the ID codes in the ArrayList.
Thanks
Earlier, before you edited your question, you had wrong getter methods.
Instead of
public void getId(int id){
}
you should write this:
public int getId() {
return id;
}
Declare your fields in Transaction class as private.
Then change your other getters in the similar way.
About your actual question, you can use for-each loop:
public static void searchTransactions(ArrayList<Transaction> argList) {
try (Scanner input = new Scanner(System.in)) {
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for (Transaction transaction : argList) {
if (transaction.getId() == searchId) {
System.out.println("Yes");
break;
}
}
}
}
If you insist for i loop, change it this way:
for (int i = 0; i < argList.size(); i++) {
if(argList.get(i).getId() == searchId){
System.out.println("Yes");
break;
}
}
ArgId is a property of the objects in the list, not a property of the list itself which is why the compiler is giving you an error.
Looks like a typo:
You have:
argList.argId.get(i).contains(searchId)
try using:
argList.get(i).argId.contains(searchId)
argList is a collection, then you get object, read argId and check if it contains searchId
I would suggest to encapsulate class Transaction:
public class Transaction {
private int id;
private char type;
private double amount;
private String description;
public Transaction(int argId, double argAmount, char argType, String argDescription) {
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public int getId() {
return id;
}
public char getType() {
return type;
}
public double getAmount() {
return amount;
}
public String getDescription() {
return description;
}
}
Then main class will look in this way:
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1: ; addTransaction(argList);
break;
case 2: ;// Search Transaction
break;
case 3: ;// Filter Withdraws and Deposits
break;
case 4: ;// Display transactions
break;
case 5: System.out.println("End");
break;
default: System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription)
);
}
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.get(i).getId()==searchId){
System.out.println("Yes");
}
}
}
}
This is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
while(true){
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
while (empList.hasItems()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
I want to make a program that accepts queue and then can also dequeue. in case 1 i made the queue successfully, but at case 2, i encountered a certain trouble that I cant figure out that I have to stack overflow it, Im stuck here and I might just be missing out the trivial things on this code. So I need your help. Why does in case 2 my dequeue gets passed an empty list? How do i fix this? Thank you very much!
when you populate your hlist you dequeue all elements from empList and hence your empList will be empty at last.
while (q.hasItems()) list.addLast(q.dequeue());
You can rewrite your addItems method, to just iterate over the elements in the given queue and add them to its own LinkedList.
I'm involved in a group assignment where we are supposed to create a bank program. This is our first time programming in java. We are stuck and we are having trouble figuring out how to connect our customer and account classes. They both consist of ArrayLists and we want the customer arraylists to contain the accounts. So that if we delete a customer, the accounts that belong to that customer will also be deleted. Can anyone give us a push in the right direction?
This is our main class which contains the bank menu:
package bank6;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Bankmenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Customer client = new Customer();
Account bank = new Account();
Account accs = new Account();
Customer cust1, cust2, cust3;
cust1 = new Customer("8905060000", "Henrik");
cust2 = new Customer("8910210000", "Emelie");
cust3 = new Customer("8611040000", "Fredrik");
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
client.addCustomerAr(cust1);
client.addCustomerAr(cust2);
client.addCustomerAr(cust3);
int ChoiceOne = 0;
int CustChoice;
int currentCustomer;
int currentAccount;
int amountC;
int amountD;
int editCust;
String personNummer = null;
String Pnr = "0";
int AdminChoice;
/*prompts the user to set ChoiceOne equal to 1 or 2. Hasnextint checks
if the input is an int. else asks for new input. */
while (ChoiceOne != 1 && ChoiceOne != 2) {
System.out.println("Press 1 to login as customer or 2 to login as admin ");
if (input.hasNextInt()) {
ChoiceOne = input.nextInt();
System.out.println();
} else {
System.out.println("You must enter number 1 or number 2");
input.next();
}//ends else
}//ends while
/*
If the user chooses 1 in the previous question, the user will be sent to
the interface for the customer. User is then asked to enter his social
security number and this number will be checked using the Luhn algoritm. Since
the scanner input is already used we added a new Scanner calleds nexLine
to deal with custPnr as a string.
(http://stackoverflow.com/questions/5032356/using-scanner-nextline)
*/
if (ChoiceOne == 1) {
//boolean quit=false;
while ("0".equals(Pnr)) {
// System.out.println("Welcome customer. Please login by using your birthdate (yymmddnnnn) ");
// Scanner nextLine = new Scanner(System.in);
// Pnr = nextLine.nextLine();
//Luhn.checkLogin(Pnr);
//Här måste en kontroll med Luhn algoritmen göras.
// getUserBirthdate();
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
/* }
Sets "quit" to false and executes quit=true if customer chooses case 0
*/
}
boolean quit = false;
do {
// boolean quit = false;
//System.out.println();
System.out.println("Logged on as " + personNummer);
System.out.println("1. deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
CustChoice = input.nextInt();
switch (CustChoice) {
case 1: //Deposit money
System.out.println(bank.getAccountNumbersFor(personNummer));
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to deposit:");
amountC = input.nextInt();
System.out.println(bank.creditAccount(currentAccount, amountC));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 2://Withdraw money
// System.out.println(bank.getAccNosFor(custPnr));
bank.getAccountNo();
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to withdraw:");
amountD = input.nextInt();
System.out.println(bank.debitAccount(currentAccount, amountD));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 3://Check ballance and accounts
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends if
else if (ChoiceOne == 2) {
while ("0".equals(Pnr)) {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
}
//AdminpNr = input.nextInt();
//Här måste en kontroll av AdminpNr göras med hjälp av Luhn.
boolean quit = false;
do {
System.out.println("1. Add customer");
System.out.println("2. Add account");
System.out.println("3. List customer");
System.out.println("4. List accounts");
System.out.println("5. Remove customer");
System.out.println("6. Remove account");
System.out.print("Your choice, 0 to quit: ");
AdminChoice = input.nextInt();
switch (AdminChoice) {
case 1://add customer
int i = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<String, Customer> testCustomers = new HashMap<String, Customer>();
String name = scan.nextLine();
//System.out.println("Att arbeta på bank ska vara jobbigt, skriv in det igen:");
//String pnummer = scan.nextLine();
String pnummer = name;
System.out.println("Skriv in namn:");
String kundnamn = scan.nextLine();
Customer obj = new Customer(pnummer, kundnamn);
testCustomers.put(name, obj);
client.addCustomerAr(obj);
i++;
} while (i < 2);
break;
case 2://add account
int i2 = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<Long, Account> testAccs = new HashMap<Long, Account>();
Long name = scan.nextLong();
//System.out.println("Skriv in personnummer igen:");
Long own = name;
long bal = 0;
Account obt = new Account(own, bal);
testAccs.put(name, obt);
accs.addAccAr(obt);
i2++;
} while (i2 < 2);
break;
case 3:// List customer and accounts
for (String info : client.getAllClients()) {
System.out.println(info);
}
break;
case 4:
for (Long infoAcc : accs.getAllAccounts()) {
System.out.println(infoAcc);
}
break;
case 5:
// ta bort kund
break;
case 6:
// ta bort konto
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends else if
}//ends main
/* private static void getUserBirthdate() {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner (System.in);
String personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
}
*/
}//ends class
This is our Account class;
package bank6;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Account {
private ArrayList accounts;
private Object lastAcc;
public String customerSocial;
private Integer balance;
private Integer accountNumber;
private Customer owner;
private Account Customer6; // Association customer/account.
private ArrayList<Account> myAccounts = new ArrayList<Account>();
public Integer deposit;
public Integer withdraw;
static Integer accountNo = 1010;
private Long persnr;
private long balans = 0;
/*Constructor.. A account cannot exist unless it is owned by a customer*/
public Account(Customer owner, Integer balance) {
this.owner = owner;
this.balance = balance;
accountNumber = accountNo++;
}
public Account() {
accounts = new ArrayList();
}
public Account(Long persnr, long balans) {
this.persnr = persnr;
this.balans = balans;
accountNumber = accountNo++;
}
public Integer getAccountNo() {
return accountNumber;
}
public String getOwner() {
return owner.getName();
}
public Customer getOwn() {
return owner;
}
public Integer getBalance() {
return balance;
}
//credits the account with an amount of money and returns a string
public String credit(Integer anAmount) {
balance += anAmount;
// return "Account number " + accountNumber + " Has been credited with "+anAmount + " kr.";
return " " + anAmount + " kr has been deposited to " + accountNumber + "\n";
}
public boolean canDebit(Integer anAmount) {
return anAmount <= balance;
}
public String debit(Integer anAmount) {
if (this.canDebit(anAmount)) {
balance -= anAmount;
return " " + anAmount + " kr has been withdrawn from " + accountNumber + "\n";
} else {
return "Account number" + accountNo + "has insufficient funds to debit"
+ anAmount;
}
}
public void addNewAccount(Customer customer) {
accounts.add(new Account(customer, 0));
lastAcc = accounts.get(accounts.size() - 1);
System.out.println("*** New account created. ***" //+ lastAcc
+ "\n");
}
public String removeAccount(int accountNumber) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
found = true; //there is a match stop the loop
if (account.getBalance() == 0) {
iter.remove();//remove this account object
results = "Account number " + accountNumber + " has been removed";
} else {
results = "Account number " + accountNumber + " cannot be removed"
+ "as it has a balance of: " + account.getBalance();
}
}//ends if there is a match
}// end while loop
if (!found) {
results = "No such account";
}
return results;
}
public String creditAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.credit(anAmount);
found = true;//stop the loop
}
}
if (!found) {
results = "No such customer";
}
return results;
}
public String debitAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.debit(anAmount);
found = true;
}
}
if (!found) {
results = "No such Customer";
}
return results;
}
public String getAccountNumbersFor(String CustomerName) {
String details = CustomerName + " has the followinng accounts: "
+ "\n\n";
Iterator iter = accounts.iterator();
//visit all of the accounts in the ArrayList
while (iter.hasNext()) {
Account account = (Account) iter.next();
if (account.getOwner().equals(CustomerName)) {
details += " Account number " + account.getAccountNo()
+ " Balance " + account.getBalance() + "kr \n";
}//ends if
}//ends while
return details;
}
public String bankAccounts() {
String details = "ALL BANK ACCOUNTS" + "\n"
+ "-----------------" + '\n';
if (accounts.size() == 0) {
details += "There are no bank accounts";
} else {
Iterator iter = accounts.iterator();
while (iter.hasNext()) {
details += iter.next().toString() + '\n';
}
}
return details;
}
#Override
public String toString() {
return "Account " + accountNumber + ": " + owner
+ "\nBalance: " + balance + " kr.\n";
}
public Boolean authenticateUser(String login, String ssn) {
if (Luhn.checkLogin(ssn)) {
System.out.println("User authenticated");
return true;
} else {
System.out.println("Authentication refused");
return false;
}
}
public void addAccAr(Account myAccount) {
myAccounts.add(myAccount);
}
public Long getBalanceToLong() {
long balTemp = balans;
return balTemp;
}
public Long getPnTorLong() {
return persnr;
}
public Long getAccNoLong() {
long accTemp = accountNumber;
return accTemp;
}
public ArrayList<Long> getAllAccounts() {
ArrayList<Long> allAccounts = new ArrayList<>();
System.out.println("ALL ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
allAccounts.add(myAccount.getAccNoLong());
allAccounts.add(myAccount.getPnTorLong());
allAccounts.add(myAccount.getBalanceToLong());
}
return allAccounts;
}
/*
public ArrayList<String> getMyAccounts() {
ArrayList<String> ownAccounts = new ArrayList<>();
System.out.println("MY ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
ownAccounts.add(myAccount.getAccNoStr());
ownAccounts.add(myAccount.getBalanceToStr());
}
return ownAccounts;
}*/
}
This is our Customer class
package bank6;
import java.util.ArrayList;
public class Customer {
int custCounter;
//attribut
private Long socialNo;
private String name;
private ArrayList customers;
public Integer customerNumber;
static Integer custNo = 1;
private ArrayList<Customer> clients = new ArrayList<Customer>();
//konstruktor
public Customer(String socialStr, String name) {
Long socialTemp = new Long(socialStr);
this.name = name;
this.socialNo = socialTemp;
customerNumber = custNo++;
}//ends konstruktor customer6
public Customer() {
customers = new ArrayList();
}
/* Set methods*/
public void setName(String name) {
this.name = name;
}
public void setsocialNo(Long socialNo) {
this.socialNo = socialNo;
}
/* get methods */
public String getName() {
return name;
}
public String getSocialNoStr() {
String socialTemp = Long.toString(socialNo);
return socialTemp;
}
public Long getSocialNo() {
return socialNo;
}
/*toString() method*/
#Override
public String toString() {
return "\n" + "Owner: " + name + " (" + socialNo + ")";
}
public void addAccCustAr() {
}
public void addCustomerAr(Customer client) {
clients.add(client);
}
public ArrayList<String> getAllClients() {
ArrayList<String> allClients = new ArrayList<>();
System.out.println("ALL CLIENTS\n-----------");
for (Customer client : clients) {
allClients.add(client.getName());
allClients.add(client.getSocialNoStr() + "\n");
}
return allClients;
//add account
//public void addAccount(account6 account){
// accounts.add(account);
//}// ends adds account
//remove account
//public void removeAccount (account6 account) {
// accounts.remove(account);
//}//ends remove account
}
}//ends public class
This is our Luhn class
package bank6;
public class Luhn {
public static boolean checkLogin(String pnr) {
if (pnr.length() != 10) {
System.out.println("");
return false;
} else {
int length = pnr.length();
int sum = 0;
int pos = length - 1;
for (int i = 1; i <= length; i++, pos--) {
char tmp = pnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0) {
produkt = num * 1;
} else {
produkt = num * 2;
}
if (produkt > 9) {
produkt -= 9;
}
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt) {
System.out.println("Correct");
return true;
} else {
System.out.println("Invalid");
return false;
}
}
}
}
Your Account class already has a Customer field -- good.
You should give Customer an ArrayList<Account> accounts field.
And also give Customer addAccount(Account acct) and removeAccount(Account acct) methods.
Why does Customer have an ArrayList<Customer> field? That makes little sense. Should a Customer hold a list of other Customers? Why? For what purpose?
Why does Account have private ArrayList<Account> myAccounts = new ArrayList<Account>();? That also makes little sense. Should an Account hold a bunch of other Accounts? Again, for what purpose?
The Account class should logically represent one and only one Account.
Same for the Customer class -- it should logically represent only one Customer.
If you think through things logically, they usually come together, and each component of your code should make sense. If it doesn't, question why it is there.
So this code is broken:
Account bank = new Account();
//....
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
Since you're adding a bunch of Customer's to an Account object. It looks like you should have another class, a Bank class, one that can hold an ArrayList<Customer>. Wouldn't this make sense?