java - withdraw from bank account using a method - java

Building a basic bank account with Java using methods. I am creating a new method to withdraw from the bank account. This is the code that I came up with right now, but on netbeans it shows that there are errors.
I created a new method called withDrawal. This code below is for the withdrawing from account and to not let the balance in the account go below zero!
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
Java file
package grossmontbank;
import java.util.Scanner;
public class GrossmontBank
{
//class variables (global - accessible throughout this class)
//scanner object to be used throughout
private static Scanner input = new Scanner(System.in);
//array of blank accounts
private static final int MAX_ACCOUNTS = 50;
private static Account[] accounts = new Account[MAX_ACCOUNTS];
//total accounts created
private static int totalAccounts = 0;
//main class mimics a bank teller
public static void main(String[] args)
{
char choice;
//loop until 'Q' is entered
do
{
choice = getChoice(); //getChoice() will only return with a C, B, W, D or Q
if(choice != 'Q')
{
switch(choice)
{
case 'C': createAccount();
break;
case 'B': checkBalance();
break;
case 'W':
break;
case 'D':
break;
}
}
}while(choice != 'Q');
closeBank(); //outputs all account holders and 'closes' the bank
}
/*method checkBalance calls method findAccount()
* if account exists, calls Account method checkBalance()
*/
private static void checkBalance()
{
int accountIndex = findAccount();
//findAccount() returns index of account if found, -1 if not found
if(accountIndex != -1)
{
accounts[accountIndex].checkBalance();
}
else
{
System.out.println("Account does not exist");
}
}
/*method checkIfExists determines if account holder already exists
* returns true if account holder exists, false otherwise
*/
private static boolean checkIfExists(String firstName, String lastName)
{
//loops through account array to see if account name already exists
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(firstName)
&& accounts[i].getLastName().equalsIgnoreCase(lastName))
{
System.out.println("Account holder already exists. Please verify and re-enter. ");
return true;
}
}
return false;
}
/*method closeBank prints out closing statement
* prints out list of all account holders
*/
private static void closeBank()
{
System.out.println("Closing the follow accounts:");
for(int i = 0; i < totalAccounts;i++)
{
//printing an account object invokes the Account class method toString()
//prints first and last name only
System.out.printf(" %s%n",accounts[i]);
}
System.out.println("Grossmont Bank is officially closed.");
}
/*method createAccount creates a single bank account
* checks to ensure account holder does not already exist
* returns Account object
*/
private static void createAccount()
{
String first, last, initial;
boolean exists = false;
//only create a new account if MAX_ACCOUNTS has not been reached
if(totalAccounts < MAX_ACCOUNTS )
{
//loop until a new account name has been entered
do
{
System.out.print("Enter your first name: ");
first = input.next();
System.out.print("Enter your last name: ");
last = input.next();
exists = checkIfExists(first,last);
}while(exists == true);
System.out.print("Will you be making an initial deposit? Enter Yes or No: ");
initial = input.next();
//if no initial deposit, call 2 parameter constructor, otherwise call 3 param one
if(initial.equals("No"))
{
accounts[totalAccounts] = new Account(first,last);
}
else
{
System.out.print("Enter initial deposit amount: ");
accounts[totalAccounts] = new Account(first,last, input.nextDouble());
}
//increment totalAccounts created (used throughout program)
totalAccounts++;
}
else
{
System.out.println("Maximum number of accounts has been reached. ");
}
}
/*method findAccount asks for first and last name
* searchs for account holder in array
* if exists, returns array index of this account
* if doesn't exist, returns '-1'
* called from checkBalance()
*/
private static int findAccount()
{
String first, last;
System.out.print("Enter first name: ");
first = input.next();
System.out.print("Enter last name: ");
last = input.next();
//loops through account array
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(first)
&& accounts[i].getLastName().equalsIgnoreCase(last))
{
return i; //returns the index of the account
}
}
return -1; //if account not found
}
/* method getChoice() outputs options
* inputs choice from user and validates
* returns choice char
*/
private static char getChoice()
{
char choice;
//output menu options
System.out.println();
System.out.println("Welcome to Grossmont Bank. Choose from the following options: ");
System.out.println(" C - create new account");
System.out.println(" B - check your balance");
System.out.println(" D - deposit");
System.out.println(" W - withdrawal");
System.out.println(" Q - quit");
//loop until a valid input is entered
do
{
System.out.print("Enter choice: ");
choice = input.next().charAt(0);
//if choice is one of the options, return it. Otherwise keep looping
if(choice == 'C' || choice == 'B' || choice == 'D' || choice == 'W' || choice == 'Q')
return choice;
else
{
System.out.println("Invalid choice. Ensure a capital letter. Please re-enter.");
choice = '?';
}
}while(choice == '?');
return choice; //will never get here, but required to have a return statement to compile
}
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
}

Related

I want to accept full name of manager in my organization java app...i tried using sc.nextLine(); but it is showing InputMisMatch error

Below is my code focus area is case 1 and case 2. please suggest some simple ways to accept full name considering I am a beginner:
package Tester;
import java.util.Scanner;
import com.app.org.Emp;
import com.app.org.Mgr;
import com.app.org.Worker;
public class TestOrganization {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many people you want to recruit");
Emp[] org = new Emp[sc.nextInt()]; //holder array ...its not a emp object...its array type of object
boolean exit = false;
int index = 0;
while(!exit) {
System.out.println("Options\n"+"1.Hire Manager\n"+"2.Hire Worker\n"+"3.Display information of all employees\n"
+ "4.Update Performance Bonus or Hourly Rate");
switch (sc.nextInt()) {
case 1:{
if(index<org.length && index>=0) {
System.out.println("Manager Details: id, name, deptId, basic, performBonus");
org[index++] = new Mgr(sc.nextInt(),sc.nextLine(),sc.next(),sc.nextDouble(),sc.nextInt());
}else {
System.out.println("Invalid!!! index");
}
break;
}
case 2:{
if(index<org.length && index>=0) {
System.out.println("Worker Details: id, name, deptId, basic, hw, hr");
org[index++] = new Worker(sc.nextInt(),sc.nextLine(),sc.next(),sc.nextDouble(),sc.nextDouble(),sc.nextDouble());
}else System.out.println("invalid!!! index");
break;
}
case 3:{
System.out.println("Employees Details");
for (Emp e : org) {
if(e!=null)
System.out.println(e);
}
}
input:
How many people you want to recruit
5
Options
1.Hire Manager
2.Hire Worker
3.Display information of all employees
4.Update Performance Bonus or Hourly Rate
1
Manager Details: id, name, deptId, basic, performBonus
101
samarth shukla
Mixing the nextInt/nextDouble/... with the nextLine from scanner is always a bad idea.
The nextInt/nextDouble/... leave an newline character back on the Stream, which means when nextLine is called, it only picks up the newline-character, which is probably not what you want
Aside from what I commented, you can try reading each input on a separated line, using Integer.parseInt(read.nextLine()) for integer and Double.parseDouble() for double.
read.nextLine() for regular string input
Actual and Formal argument lists differ in length constructor java.
Better to use nextLine() first and then the rest.
Example :-
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
Mgr obj = new Mgr(sc.nextLine(), sc.nextDouble(), sc.nextInt());
}
}
class Mgr{
public Mgr(String name, Double dNo, int id ){
System.out.println(id +" and "+ name +"dNo "+ dNo);
}
}
Accept input in some variables and pass them to the object constructor.
Check this for more deatils https://stackoverflow.com/a/13102066/7575841
package tester;
import java.util.Scanner;
import com.app.org.Employee;
import com.app.org.Manager;
import com.app.org.Worker;
public class TestOrganisation {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.print("What is the strength of organisation ? ");
Employee[] employees = new Employee[cin.nextInt()];
int count = 0;
boolean again = true;
do {
System.out.println("***** Welcome To Virtual Organization *****");
System.out.println("1. Hire Manager");
System.out.println("2. Hire Worker");
System.out.println("3. Display All");
System.out.println("4. Update Performance Bonus/Hourly Rate");
System.out.println("0. Wrap Up");
System.out.print("Enter option number : ");
switch(cin.nextInt() ) {
case 1:
if (count < employees.length) {
System.out.println("Hire a new manager.");
System.out.print("Enter Employee ID : ");
int id = cin.nextInt();
System.out.print("Enter Departemnt ID : ");
int deptID = cin.nextInt();
cin.nextLine();
System.out.print("Enter Name : ");
String name = cin.nextLine();
System.out.print("Enter Basic Salary : ");
double basic = cin.nextDouble();
System.out.print("Enter Performance Bonus : ");
double perfBonus = cin.nextDouble();
employees[count++] = new Manager(id, deptID, name, basic, perfBonus);
System.out.println("Manager Hired Successfully.\n");
}
else {
System.out.println("\nNo more vacancy available.\n");
}
break;
case 2:
if (count < employees.length) {
System.out.println("Hire a new worker.");
System.out.print("Enter Employee ID : ");
int id = cin.nextInt();
System.out.print("Enter Departemnt ID : ");
int deptID = cin.nextInt();
cin.nextLine();
System.out.print("Enter Name : ");
String name = cin.nextLine();
System.out.print("Enter Basic Salary : ");
double basic = cin.nextDouble();
System.out.print("Enter Hourly Rate : ");
double hourlyRate = cin.nextDouble();
System.out.print("Enter Hours Worked : ");
int hoursWorked = cin.nextInt();
employees[count++] = new Worker(id, deptID, name, basic, hourlyRate, hoursWorked);
System.out.println("Wroker Hired Successfully.\n");
}
else {
System.out.println("\nNo more vacancy available.\n");
}
break;
case 3:
if (count == 0) {
System.out.println("\nOnly Ghosts Work Here.\n");
}
else {
System.out.println("\nList of employees work in organization.");
for (Employee e: employees) {
if (e instanceof Worker) {
System.out.print(e);
System.out.println(", whose net salary is " + ((Worker)e).computeNetSalary());
}
else if (e instanceof Manager) {
System.out.print(e);
System.out.println(", whose net salary is " + ((Manager)e).computeNetSalary());
}
else {
System.out.println("Position is either empty or a ghost works here.");
}
}
System.out.println();
}
break;
case 4:
if (count == 0) {
System.out.println("\nOnly Ghosts Work Here.\n");
}
else {
System.out.print("Enter Employee ID : ");
int empID = cin.nextInt();
for (Employee e: employees) {
if (e != null) {
if(e.equals(empID)) {
if (e instanceof Worker) {
System.out.print("Enter new hourly rate : ");
double hourlyRate = cin.nextDouble();
((Worker) e).setHourlyRate(hourlyRate);
System.out.println("Hourly Rate Updated.\n");
}
else if (e instanceof Manager) {
System.out.print("Enter new performance bonus : ");
double prefBonus = cin.nextDouble();
((Manager) e).setPerfBonus(prefBonus);
System.out.println("Performance Bonus Updated.\n");
}
else {
System.out.printf("\nEmployee with %id is a ghost.\n", empID);
}
}
break;
}
}
}
break;
case 0:
again = false;
System.out.println("Good Bye. Have a nice day.");
break;
default:
System.out.println("Invalid Option. Please Try Again.");
}
} while(again);
cin.close();
}
}

Failed Logic in project

The purpose of the project is to gather user input and output certain prices based on your input. When entering data, it seems as if none of my logic is working and it is returning 0 for a value.
PS. The problem that is wrong is the total price of the cell phone plan. When i call my methods from the main method everything runs but I am assuming my equations aren't correct.
import java.util.Scanner; // gathers user input
public class Exam2Hassan {
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
int numOfPhones = 0, choice = 0;
double finalCost = 0, basePrice = 0, cellPlanCost = 0;
char goAgain;
// holds menu selection
final int MENU_OPTION_ONE = 1;
final int MENU_OPTION_TWO = 2;
final int MENU_OPTION_THREE = 3;
final int MENU_OPTION_FOUR = 4;
// calls all methods
displayData();
basePrice = basePricing(choice);
cellPlanCost = calculateCost(numOfPhones, basePrice);
finalCost = displayFinalCost(cellPlanCost);
} // end main
/**
This method displays the data plan menu, should not accept any arguments or return any value
*/
public static void displayData() {
Scanner keyboard = new Scanner(System.in); // allows user input
int choice, numOfPhones;
double cellPlanCost = 0;
double totalCost = 0;
char goAgain;
System.out.print("Data Plan Menu: ");
System.out.println();
System.out.println();
System.out.println("\t1. 1 GB");
System.out.println("\t2. 2 GB");
System.out.println("\t3. 3 GB");
System.out.println("\t4. 4 GB");
System.out.println();
do { // allows user to input how many plans they want to process
System.out.print("Select a plan from the menu above: ");
choice = keyboard.nextInt();
while(choice < 1 || choice > 4)//validate the user's input
{
System.out.print("Selection must be between 1 and 4. Select a plan from the menu above: ");
choice = keyboard.nextInt();
}
System.out.print("Enter the number of phones: ");
numOfPhones = keyboard.nextInt();
while(numOfPhones < 1) //validate the user's input
{
System.out.print("Number of phones must be at least 1. Enter the Number of phones: ");
numOfPhones = keyboard.nextInt();
}
System.out.printf("The total price of the cell phone plan (before tax and fees) is: $%.2f\n", totalCost);
System.out.println();
keyboard.nextLine();
System.out.println();
System.out.print("Do you wish to calculate the price of another plan (Y/N)? ");
goAgain = keyboard.nextLine().charAt(0);
System.out.println();
}
while(goAgain == 'Y' || goAgain == 'y');
}
/**
This method accepts the menu selection as an argument and shows which data plan was selected. should return base pricing
*/
public static double basePricing(int choice){
final double ONE_GB = 34.99;
final double TWO_GB = 49.99;
final double FOUR_GB = 64.99;
final double UNLIMITED_GB = 74.99;
double basePrice = 0;
if(choice == 1) {
basePrice = 34.99;
}
else if(choice == 2) {
basePrice = 49.99;
}
else if(choice == 3) {
basePrice = 64.99;
}
else if(choice == 4) {
basePrice = 74.99;
}
return basePrice;
}
/**
This method calculates the cost of a cell plan. Accepts number of lines and base pricing. returns the cost of the plan
*/
public static double calculateCost(int numOfPhones, double basePrice) {
double cellPlanCost = 0;
cellPlanCost = basePrice + (10.00 * numOfPhones);
return cellPlanCost;
}
/**
This method should display the final cost. accepts the final cost as argument
*/
public static double displayFinalCost(double cellPlanCost) {
return cellPlanCost;
}
} // end class
Immediately after entering the number of phones , there are no logic to calculate cost before printing.
I would suggest you to call following methods after entering number of phones inside the displayData() method and use finalCost or appropriate variable based on your requirement.
basePrice = basePricing(choice);
cellPlanCost = calculateCost(numOfPhones, basePrice);
finalCost = displayFinalCost(cellPlanCost);
Below is the code for the same.
import java.util.Scanner; // gathers user input
public class Exam2Hassan {
public static void main(String [] args) {
// calls all methods
displayData();
} // end main
/**
This method displays the data plan menu, should not accept any arguments or return
any value
*/
public static void displayData() {
Scanner keyboard = new Scanner(System.in); // allows user input
int choice, numOfPhones;
double cellPlanCost = 0;
double basePrice=0;
char goAgain;
System.out.print("Data Plan Menu: ");
System.out.println();
System.out.println();
System.out.println("\t1. 1 GB");
System.out.println("\t2. 2 GB");
System.out.println("\t3. 3 GB");
System.out.println("\t4. 4 GB");
System.out.println();
do { // allows user to input how many plans they want to process
System.out.print("Select a plan from the menu above: ");
choice = keyboard.nextInt();
while(choice < 1 || choice > 4)//validate the user's input
{
System.out.print("Selection must be between 1 and 4. Select a plan from the menu above: ");
choice = keyboard.nextInt();
}
basePrice=basePricing(choice);
System.out.print("Enter the number of phones: ");
numOfPhones = keyboard.nextInt();
while(numOfPhones < 1) //validate the user's input
{
System.out.print("Number of phones must be at least 1. Enter the Number of phones: ");
numOfPhones = keyboard.nextInt();
}
cellPlanCost = calculateCost(numOfPhones, basePrice);
System.out.printf("The total price of the cell phone plan (before tax and fees) is: $%.2f\n", cellPlanCost);
System.out.println();
keyboard.nextLine();
System.out.println();
System.out.print("Do you wish to calculate the price of another plan (Y/N)? ");
goAgain = keyboard.nextLine().charAt(0);
System.out.println();
}
while(goAgain == 'Y' || goAgain == 'y');
}
/**
This method accepts the menu selection as an argument and shows which data plan was
selected. should return base pricing
*/
public static double basePricing(int choice){
double basePrice = 0;
if(choice == 1) {
basePrice = 34.99;
}
else if(choice == 2) {
basePrice = 49.99;
}
else if(choice == 3) {
basePrice = 64.99;
}
else if(choice == 4) {
basePrice = 74.99;
}
return basePrice;
}
/**
This method calculates the cost of a cell plan. Accepts number of lines and base
pricing. returns the cost of the plan
*/
public static double calculateCost(int numOfPhones, double basePrice) {
double cellPlanCost = 0;
cellPlanCost = basePrice + (10.00 * numOfPhones);
return cellPlanCost;
}
/**
This method should display the final cost. accepts the final cost as argument
*/
public static double displayFinalCost(double cellPlanCost) {
return cellPlanCost;
}
} // end class

Does my add method do too much work?

I'm new to programming and I keep making the mistake of having a method do too much work. My TA gave me some advice that I should aim to make a method reusable enough that I can use it in another program without having to really modify very much. This definitely helped me approach writing methods in a better way, but I'm worried that I might have made my "add" method too meaty. Should I split it up or is it technically doing "one thing" even though it's pretty chunky?
Here's my main class (the referenced classes are just basic templates that don't do anything special aside from having getters and setters so I won't bother posting them here):
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
enum ClassStanding{FRESHMAN,SOPHOMORE,JUNIOR,SENIOR,UNKNOWN,MASTERS_STUDIES,PHD_STUDIES};
enum Major{CS,CEG,EE,ISE,BME,ME,MET,UNKNOWN};
enum StudentType{UNDERGRADUATE,GRADUATE,UNDECLARED};
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<>();
int counter;
boolean continueInput;
int contCounter;
do {
do {
System.out.print("Please enter what you want to do-ADD, REMOVE, LIST, or SAVE: ");
switch (stdin.next().toLowerCase()) {
case "add": add(stdin, studentList); counter = 0; break;
case "remove": counter = 0; break;
case "list": counter = 0; break;
case "save": counter = 0; break;
default: System.out.println("Improper input, please enter only ADD, REMOVE, LIST, or SAVE."); counter = 1;
}
} while (counter == 1);
do {
System.out.print("\nDo you want to continue? Yes or no: ");
switch (stdin.next().toLowerCase()) {
case "yes": contCounter = 0; continueInput = true; break;
case "no": contCounter = 0; continueInput = false; break;
default: contCounter = 1; continueInput = false; System.out.print("\nPlease only enter 'yes' or 'no'.");
}
} while (contCounter == 1);
} while (continueInput);
} // end main method
public static void add(Scanner stdin, ArrayList<Student> studentList) { // this is the one
String firstName;
String lastName;
String uid;
StudentType studentType;
ClassStanding studentClassStanding;
Major major;
double overallGPA;
double majorGPA;
String majorProfessor;
boolean thesisOption;
System.out.print("Please enter the student's first name: ");
String tempName = stdin.next();
firstName = checkName(tempName);
System.out.print("Please enter the student's last name: ");
tempName = stdin.next();
lastName = checkName(tempName);
System.out.println("Please enter the student's UID in the format 'U####' or 'U#####': ");
String tempUID = stdin.next();
uid = checkUID(tempUID).toUpperCase();
int count;
do {
System.out.print("Please enter the student's status as UNDECLARED, UNDERGRADUATE, or GRADUATE: ");
switch (stdin.next().toUpperCase()) {
case "UNDECLARED":
studentType = StudentType.UNDECLARED;
studentClassStanding = setStudentClassStanding(studentType);
count = 0;
Student student = new Student(firstName, lastName,
uid, studentType, studentClassStanding);
studentList.add(student);
break;
case "UNDERGRADUATE":
studentType = StudentType.UNDERGRADUATE;
major = setMajor();
studentClassStanding = setStudentClassStanding(studentType);
System.out.println("Enter the student's overall GPA below.");
overallGPA = setGPA();
System.out.println("Enter the student's major GPA below.");
majorGPA = setGPA();
count = 0;
UnderGraduate underGraduate = new UnderGraduate(firstName, lastName, uid, studentType,
studentClassStanding, major, overallGPA, majorGPA);
studentList.add(underGraduate);
break;
case "GRADUATE":
studentType = StudentType.GRADUATE;
studentClassStanding = setStudentClassStanding(studentType);
majorProfessor = setMajorProfessor();
thesisOption = setThesisOption();
count = 0;
Graduate graduate = new Graduate(firstName, lastName, uid, studentType,
studentClassStanding, majorProfessor, thesisOption);
studentList.add(graduate);
break;
default:
System.out.println("Please enter either Undeclared, Undergraduate, or Graduate only.");
count = 1;
}
} while (count == 1);
}
public static String checkName(String tempName) {
int a = 1;
String name1;
Scanner scanner = new Scanner(System.in);
do {
name1 = tempName; // hold the value of firstName in name1
for (int i = 0; i < tempName.length(); i++) { // loop to check input consists of letters (is a name)
if (!Character.isLetter(tempName.charAt(i))) { // if non-letters detected, ensure this was intentional
System.out.println("Please ensure you've entered the correct name. Re-enter the name or enter 'continue' to proceed: ");
tempName = scanner.nextLine();
if (tempName.equalsIgnoreCase("continue")) { // if user enters "continue", use original input
a = 0;
tempName = name1; // pass name1 value to firstName
break;
} else {
a = 1; // continue prompting for firstName
}
} else { // accept input
a = 0;
}
}
} while (a == 1); // loop to ensure proper input
return tempName;
} // end checkName method
public static String checkUID(String tempUID) {
Scanner scan = new Scanner(System.in);
int a;
do {
if (tempUID.charAt(0) == 'U' || tempUID.charAt(0) == 'u') {
if (tempUID.length() == 6 || tempUID.length() == 5) {
a = 0;
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} while (a == 1);
return tempUID;
} // end checkUID method
public static ClassStanding setStudentClassStanding(StudentType studentType) {
Scanner scan = new Scanner(System.in);
int count;
ClassStanding studentTempClassStanding = null;
do {
if (studentType == StudentType.UNDECLARED || studentType == StudentType.UNDERGRADUATE) {
System.out.print("Please enter the student's class standing as either Freshman, Sophomore, Junior, Senior, or Unknown: ");
switch (scan.next().toUpperCase()) {
case "FRESHMAN":
studentTempClassStanding = ClassStanding.FRESHMAN;
count = 0;
break;
case "SOPHOMORE":
studentTempClassStanding = ClassStanding.SOPHOMORE;
count = 0;
break;
case "JUNIOR":
studentTempClassStanding = ClassStanding.JUNIOR;
count = 0;
break;
case "SENIOR":
studentTempClassStanding = ClassStanding.SENIOR;
count = 0;
break;
case "UNKNOWN":
studentTempClassStanding = ClassStanding.UNKNOWN;
count = 0;
break;
default:
System.out.println("Please enter only Freshman, Sophomore, Junior, Senior, or Unknown.");
count = 1;
}
} else {
System.out.print("Please enter the student's class standing as either 'Masters' for Masters Studies or 'PhD' for PhD Studies: ");
switch (scan.next().toUpperCase()) {
case "MASTERS": studentTempClassStanding = ClassStanding.MASTERS_STUDIES; count = 0; break;
case "PHD": studentTempClassStanding = ClassStanding.PHD_STUDIES; count = 0; break;
default: System.out.println("Please enter only 'Masters' or 'PhD'.");
count = 1;
}
}
} while (count == 1);
return studentTempClassStanding;
} // end setStudentClassStanding method
public static Major setMajor() {
Major tempMaj = null;
Scanner s = new Scanner(System.in);
int c;
do {
System.out.print("Please enter the student's major as either CS, CEG, EE, ISE, BME, ME, MET, or Unknown: ");
switch (s.next().toUpperCase()) {
case "CS":
tempMaj = Major.CS;
c = 0;
break;
case "CEG":
tempMaj = Major.CEG;
c = 0;
break;
case "EE":
tempMaj = Major.EE;
c = 0;
break;
case "ISE":
tempMaj = Major.ISE;
c = 0;
break;
case "BME":
tempMaj = Major.BME;
c = 0;
break;
case "ME":
tempMaj = Major.ME;
c = 0;
break;
case "MET":
tempMaj = Major.MET;
c = 0;
break;
case "UNKOWN":
tempMaj = Major.UNKNOWN;
c = 0;
break;
default:
System.out.println("Please enter only the specified values. ");
c = 1;
}
} while (c == 1);
return tempMaj;
} // end setMajor method
public static double setGPA() {
Scanner s = new Scanner(System.in);
double gpa;
int a;
do {
try {
System.out.print("Please enter the student's GPA: ");
gpa = s.nextDouble();// read in the gpa
if (gpa < 0.0 || gpa > 4.0) { // ensure the gpa is in the correct range
System.out.println("Invalid input, please enter a positive value between 0.0 and 4.0.");
a = 1;
} else {
a = 0;
}
} catch (InputMismatchException ex) { //catch any exceptions, prompt for correct input
a = 1;
gpa = 0.0;
System.out.println("Sorry, please enter a double value.");
s.nextLine(); // skip the last input
}
} while (a == 1 || gpa < 0.0 || gpa > 4.0); //loop while gpa is negative or incorrect input is received
return gpa;
} // end setGPA method
private static String setMajorProfessor() {
Scanner s = new Scanner(System.in);
String prof;
System.out.print("Please enter the name of the major professor: ");
String tempName = s.nextLine();
prof = checkName(tempName);
return prof;
} // end setMajorProfessor method
private static boolean setThesisOption() {
Scanner s = new Scanner(System.in);
boolean thesis = false;
int a;
do {
System.out.print("Please enter 'yes' if a thesis will be written, otherwise enter 'no': ");
switch (s.next().toUpperCase()) {
case "YES": thesis = true; a = 0; break;
case "NO": thesis = false; a = 0; break;
default: System.out.println("Please enter only 'yes' or 'no'."); a = 1;
}
} while (a == 1);
return thesis;
} // end setThesisOption method
}
The focus of this project is to have a menu of options for the user (add, list, save, sort, remove) that will allow them perform a series of operations on an arraylist they supply (through the add function). Obviously I'm not done and I'm not looking for help on my project, I'm just wondering if I made my "add" method too meaty. I tried to break it up as best I could by calling other methods to do a lot of the work in it, but I still feel like it might be too much work for the method. But then again it could be fine, I really don't know-I haven't yet gotten a feel for how much a method should really do.
Yes, this definitely does too much.
In software design, people have introduced what they call bad smells, GRASP patterns and design patterns to give more scientific arguments to a discussion.
Bad smells: also called antipatterns. They include for instance god class (a class that does everything), seems very applicable here. These are alarms that you should refactor your code.
GRASP patterns: these are more or less the directions in which your code should move. Two applicable here are controller and low coupeling: split I/O and data manipulation from each other and definitely make sure that most methods don't need data provided/stored by other methods/classes.
Design patterns: these are a set of patterns one can apply to achieve the GRASP patterns. For instance you can use a Factory to built new instances, or use a Chain of Responsiblity to split a problem into small subproblems that are handled separately.
Some final advices by quotes:
"Two or more, use a for" - E. W. Dijkstra
"A method should in most circumstances not contain more than 15 lines" - Some of my teachers
There are some rules and there are some tools to help with those rules. Basically using a static code analyzer helps to determine whether the method is too big or doing too many things. Findbugs is one of the famous static code analyzer.

Java: setting variable on object array

public class ParkingLotApplication {
static Scanner input = new Scanner(System.in);
public static ParkingDescription[][] ParkingLot = new ParkingDescription[3][15];
public StudentDescription StudDesc = new StudentDescription();
static int i = 0;
static int j = 0;
static int parkLevel = 0;
static int parkSlot = 0;
public static void main(String[] args) {
// TODO: Add your code here
ParkingLotApplication PA = new ParkingLotApplication();
PA.menu();
}
public void menu() {
Scanner input = new Scanner(System.in);
System.out.println("WELCOME TO CAR PARK SYSTEM");
System.out.println("Enter your name: ");
String nm = input.nextLine();
System.out.println("Enter your password: ");
int pass = input.nextInt();
if ((nm.equals("admin12")) && (pass == 12345)) {
Login();
} else {
menu();
}
}
public void Login() {
System.out.println("|----------------------------------|");
System.out.println("| Admin Menu |");
System.out.println("|----------------------------------|");
System.out.println("| N- New Registration |");
System.out.println("| U- Update Data |");
System.out.println("|----------------------------------|");
char ch = input.next().charAt(0);
switch (ch) {
case 'N':
case 'n':
Reg();
break;
case 'U':
case 'u':
UpdatePark();
break;
default:
System.out.println("Choose Again!");
Login();
break;
}
}
public void Reg() {
System.out.println();
System.out.println(" **Parking Lot** ");
System.out.println(" ________________________________________________________________________________");
for (i = 0; i < 3; i++) {
for (j = 0; j < 15; j++) {
ParkingLot[i][j] = new ParkingDescription();
System.out.print(" * " + ParkingLot[i][j].getStatus());
}
System.out.println();
System.out.println(" ********************************************************************************");
}
System.out.println("Please insert number 1-3 to choose the parking level");
parkLevel = input.nextInt();
System.out.println("Please insert number 1-15 to choose the parking slot");
parkSlot = input.nextInt();
//check available
if (parkLevel == 1) {
ParkingLot[0][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[0][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[0][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 2) {
ParkingLot[1][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[1][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[1][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 3) {
ParkingLot[2][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[2][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[2][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
}
}
public void UpdatePark() {
System.out.println();
System.out.println(" **Parking Lot** ");
System.out.println(" ________________________________________________________________________________");
for (i = 0; i < 3; i++) {
for (j = 0; j < 15; j++) {
ParkingLot[i][j] = new ParkingDescription();
System.out.print(" * " + ParkingLot[i][j].getStatus());
}
System.out.println();
System.out.println(" ********************************************************************************");
}
System.out.println("Please insert number 1-3 to choose the parking level");
parkLevel = input.nextInt();
System.out.println("Please insert number 1-15 to choose the parking slot");
parkSlot = input.nextInt();
//check available
if (parkLevel == 1) {
ParkingLot[0][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[0][parkSlot - 1].getAvailable() == false) {
ParkingLot[0][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 2) {
ParkingLot[1][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[1][parkSlot - 1].getAvailable() == true) {
ParkingLot[1][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 3) {
ParkingLot[2][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[2][parkSlot - 1].getAvailable() == true) {
ParkingLot[2][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
}
}
}
//Class parking description
public class ParkingDescription {
public static int StudID, ParkSpaceID, DReg;
public static String Status, CNum;
public static Boolean Available = true;
public ParkingDescription() {
// TODO: Add your code here
}
public void setPark(int parkSpaceID, Boolean available, StudentDescription StDe)
{
this.StudID = StDe.getStudentID();
this.CNum = StDe.getCarNumber();
this.DReg = StDe.getDateReg();
this.ParkSpaceID = parkSpaceID;
this.Available = available;
}
public Boolean getAvailable()
{
return Available;
}
public String getStatus()
{
if(Available == false){
return "1";
} else {
return "0";
}
}
public void showDetails()
{
//generate report
System.out.println("Student ID : TP"+StudID);
System.out.println();
System.out.println("Car Number : "+CNum);
System.out.println();
System.out.println("Parking Space : L"+ParkSpaceID);
System.out.println();
System.out.println("Date Register : "+DReg);
}
}
//Student class
public class StudentDescription {
public int StudentID, CNumber, DateReg;
public String FName, LName, EMail, CarNum;
public StudentDescription() {
// TODO: Add your code here
}
public void setStudDesc(int studentID, String fName, String lName, int cNumber, String eMail, String carNum, int dateReg)
{
this.StudentID = studentID;
this.FName = fName;
this.LName = lName;
this.CNumber = cNumber;
this.EMail = eMail;
this.CarNum = carNum;
this.DateReg = dateReg;
}
public int getStudentID()
{
return this.StudentID;
}
public String getCarNumber()
{
return this.CarNum;
}
public int getDateReg()
{
return this.DateReg;
}
}
I have this problem. when i want to set one parking detail object into ParkingLot array, the array is insert same data information on all of array. the output suppose to be like this:
**Parking Lot**
* 1 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
* 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
* 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
but I got all the output being set to 1. So how to solve this problem? thanks..
There's still lots of code that you haven't shown, for example, the code for the ParkingDescription class. But based on what you HAVE shown ...
In the chunk of code that prints out all the statuses, (which for some reason, you've coded twice - once in Reg and once in UpdatePark), you are populating your array with 45 new ParkingDescription objects, and printing the status of each one. That is, you're throwing away all the ParkingDescription objects that you had previously, and only printing brand new objects. You really don't want to do that, because it's the ParkingDescription objects that store all the data that the user has entered.
I guess you're getting all 1s because 1 is the status of a new ParkingDescription.
UPDATE
Now that you've shown your ParkingDescription class, I see that the problem is that you've declared its fields as static. That means that there's only one copy of each field, shared between all the instances of this class. Remove the word static from the field declarations, and the problem should be fixed.
And the next time you post a question on Stack Overflow, I strongly recommend posting ALL the code when you first post the question. Don't just post the part where YOU think the bug is, because you waste everyone's time if you're wrong.

do-while loop not terminate when answer no

package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
CreditCardNumber[] cred1;
CreditCardNumber cred2 = getInput();
Display("The complete number from your input:", cred2);
cred1 = getInputArray();
DisplayArray(cred1);
TryAnother(cred1);
}
public static CreditCardNumber getInput() {
String ID;
String accNum;
CreditCardNumber tempCred;
System.out.printf("Please enter issuer ID:");
ID = scanner.next();
System.out.printf("Please enter account number:");
accNum = scanner.next();
tempCred = new CreditCardNumber(ID, accNum);
return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2) {
System.out.println(ch);
System.out.println(cred2.toString().replaceAll(".{4}", "$0 "));
}
public static CreditCardNumber[] getInputArray() {
CreditCardNumber[] tempArray;
String tempID;
int size;
System.out.printf("Please enter size of the aray:");
size = scanner.nextInt();
if(size < 1) {
size = 1;
}
tempArray = new CreditCardNumber[size];
System.out.printf("Please enter issuer ID:");
tempID = scanner.next();
for(int i = 0; i < tempArray.length; i++) {
tempArray[i] = new CreditCardNumber();
tempArray[i].CreateCred(tempID);
}
return tempArray;
}
public static void DisplayArray(CreditCardNumber[] cred1) {
for(int i = 0; i< cred1.length; i++) {
Display("Credit Card # " + i+":" + '\n', cred1[i]);
}
System.out.println();
}
public static boolean TryAnother(CreditCardNumber[] cred1) {
String s;
System.out.printf("Get more credit card numbers? (n for no):");
s = scanner.next();
if(s.charAt(0) != 'N' || s.charAt(0) != 'n') {
do {
TryAnother(cred1);
cred1 = getInputArray();
DisplayArray(cred1);
} while(s.charAt(0) != 'N' || s.charAt(0) != 'n');
}
return false;
}
}
Hi, I have a problem in my do-while loop in TryAnother method, I'm trying to get the code to repeat for some reason when I enter no the process does not terminate when the condition of the do while loop said it should terminate also it repeat the line that tell user to enter 'yes' or 'no'.
something like:
Please enter issuer ID:321321
Please enter account number:654654654
The complete number from your input:
3213 2165 4654 6549
Please enter size of the aray:7
Please enter issuer ID:789789
Credit Card # 0:
7897 8985 6852 9257
Credit Card # 1:
7897 8917 0678 9958
Credit Card # 2:
7897 8900 5781 0934
Credit Card # 3:
7897 8949 2244 6098
Credit Card # 4:
7897 8941 3828 4895
Credit Card # 5:
7897 8965 9233 5006
Credit Card # 6:
7897 8981 8442 5880
Get more credit card numbers? (n for no):n
Get more credit card numbers? (n for no):n
Get more credit card numbers? (n for no):no
Get more credit card numbers? (n for no):
As you can see when I enter no. it keeps repeating the same sentence. What I want is for it to repeat from enter the array size sentence, How can I do this?
Change this:
}while(s.charAt(0) != 'N' || s.charAt(0) != 'n');
to:
}while(s.charAt(0) != 'N' && s.charAt(0) != 'n');

Categories

Resources