Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: Putting an exception in an method

  1. #1
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Putting an exception in an method

    Hello, long time no see!

    Now my problem is the following, I have the following exception that I created

     
    package banking;
     
    public class NoSuchAccountException extends AccountException {
     
    	public NoSuchAccountException(int accountNo) {
    		super(message,accountNo);
     
     
    	}
    }

    As you can tell, this exception tells us when there is no account with the searched account number.The question is where in this Account class do i implement this exception, and how do I check if the account with that account number exist, so that if it doesnt exist I can throw this exception.


     
    package banking;
     
    import io.In;
    import io.Out;
    import java.io.IllegalArgumentException;
     
    class Account {
      final int accountNo;
      final Customer owner;
      final double overdraft;
     
      double balance = 0;
     
      private Account(int accountNo, Customer owner, double overdraft) {
        this.accountNo = accountNo;
        this.owner = owner;
        this.overdraft = overdraft;
      }
     
      void print() {	  
        Out.println("Kontonummer: " + accountNo);
        owner.print();
        Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n",
          balance, overdraft);
      }
       public int createAccount(String firstName, String lastName, String phone, double overdraft) throws BankServiceException {
        if (nOfAccounts == CAPACITY) 
    		throw new BankServiceException("The maximum capacity has been reached!");
     
        // use nOfAccounts as accountNo and index to array
        Customer owner = new Customer(firstName, lastName, phone);
        Account account = new Account(nOfAccounts, owner, overdraft);
        accounts[nOfAccounts] = account;
        nOfAccounts++;
     
        return account.accountNo;
      }
      public boolean deposit(double amount) throws IllegalArgumentException {
        if (amount <= 0) {
    		throws new IllegalArgumentException("Cannot deposit negative amounts!");
    	}
    	break;
    	else {
        balance += amount;
        return true;
      }
     
      public boolean withdraw(double amount) throws OverdraftLimitReachedException {
        if (amount <= 0 ) {
    		throw new OverdraftLimitReachedException("Cannot withdraw negative amounts!",accountNo);
    		break;
    	}
    	  else if  !isCovered(amount)) {
    	  return false;
      } else {
        balance -= amount;
        return true;
      }
     
      boolean isCovered(double amount) {
        return amount - overdraft <= balance;
      }
     
      boolean transfer(Account target, double amount) {
        boolean success = withdraw(amount);
        if (!success) return false;
     
        target.deposit(amount);
        return true;
      }
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    where in this Account class do i implement this exception
    The code currently throws exceptions when exceptional conditions are found. Not sure what this question is about.

    how do I check if the account with that account number exist
    What code creates valid account numbers? Does it save a list of valid account numbers that can be used to check for validity?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    What I meant by implementing this exception is, which method should throw the exception.And the code create account creates valid account number.After you create an account you get the account number (starting from 0) and with every new account created the account number rises (the nOfAccount++). Hopefully it gives you some insight in what I'm trying to achive, basically I'm trying to check if an account number exists, and if not to throw this exception, and catch it later.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    check if an account number exists
    How is an account number created? Is there a value or list that can be used to determine if a number is valid?
    every new account created the account number rises (the nOfAccount++)
    That looks like the valid account numbers range in value from the first account number (0 ??) to nOfAccount-1.

    I think earlier I suggested that account numbers start at a value like 2345 and the next number is +37 from the last number. A valid number would be (nbr-2345) mod 37 == 0
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    I dont really get that part with 2345

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    That was just an example of how to create account numbers that could make it harder for some one to create a valid number without understanding the algorithm. For your case just adding 1 will work.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    Oh okay,I'll try a few things and we will see what I get

  8. #8
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    Well okay after trying for quite a while this is what I've come up with

     
    package banking;
     
    import java.lang.IllegalArgumentException;
    import io.In;
    import io.Out;
     
    class Banking {
      static final int CAPACITY = 100;
     
      final Account[] accounts = new Account[CAPACITY];
      int nOfAccounts = 0;
     
      int createAccount(String firstName, String lastName, String phone, double overdraft) throws BankServiceException {
        if (nOfAccounts == CAPACITY) {
    		throw new BankServiceException("The maximum capacity has been reached");
    	}
        Customer owner = new Customer(firstName, lastName, phone);
        Account account = new Account(nOfAccounts, owner, overdraft);
        accounts[nOfAccounts] = account;
        nOfAccounts++;
     
        return account.accountNo;
      }
     
      private Acount getAccount(accountNo) throws NoSuchAccountException {
      if (accountNo >= accounts.length || accounts[accountNo] == null) {
       throw new NoSuchAccountException();
      }
      return account;
    }
     
     
      boolean deposit(int accountNo, double amount) {
        Account account = getAccount(accountNo);
        return account.deposit(amount);
      }
     
      public boolean withdraw(int accountNo, double amount) throws OverdraftLimitReachedException {
        if (amount > overdraft ) {
    		throw new OverdraftLimitReachedException("The overdraft limit has been excedeed");
     
        Account account = accounts[accountNo];
        return account.withdraw(amount);
    	}
      }
      public boolean transfer(int fromNo, int toNo, double amount) {
        if (fromNo < 0 || toNo < 0 ||
            fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;
     
        Account from = accounts[fromNo];
        Account to = accounts[toNo];
        return from.transfer(to, amount);
      }
     
      public double getBalance(int accountNo) {
        if (accountNo < 0 || accountNo >= nOfAccounts) return 0;
     
        Account account = accounts[accountNo];
        return account.balance;
      }
     
      double getBalance() {
        double sum = 0;
     
        for (int i = 0; i < nOfAccounts; i++) {
          sum += accounts[i].balance;
        }
        return sum;
      }
     
      void print() {
        Out.println("---------- Bankauszug ----------");
     
        for (int i = 0; i < nOfAccounts; i++) {
          accounts[i].print();
          Out.println("--------------------------------");
        }
        Out.format("Bilanzsumme: %.2f%n", getBalance());
        Out.println("--------------------------------");
      }
     
      // --------------------- Optionaler Teil ---------------------
     
      public static void main(String[] args) {
        Banking banking = new Banking();
        char op;
     
        do {
          printMenu();
          op = readOperation();
     
          switch (op) {
            case 'a': {
              printTitle("Konto anlegen");
              String firstName = getString("Vorname");
              String lastName = getString("Nachname");
              String phone = getString("Telefonnummer");
              double overdraft = getDouble("Überziehungsrahmen");
     
              int accountNo = banking.createAccount(
                firstName, lastName, phone, overdraft);
              printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
              break;
            }
            case 'e': {
              printTitle("Einzahlen");
              int accountNo = getInt("Kontonummer");
              double amount = getDouble("Einzahlungsbetrag");
     
              boolean success = banking.deposit(accountNo, amount);
              printMessage("Einzahlen", success);
              break;
            }
            case 'b': {
              printTitle("Abheben");
              int accountNo = getInt("Kontonummer");
              double amount = getDouble("Abhebungsbetrag");
     
              boolean success = banking.withdraw(accountNo, amount);
              printMessage("Abheben", success);
              break;
            }
            case 't': {
              printTitle("Überweisen");
              int fromNo = getInt("Von Kontonummer");
              int toNo = getInt("Auf Kontonummer");
              double amount = getDouble("Betrag");
     
              boolean success = banking.transfer(fromNo, toNo, amount);
              printMessage("Überweisen", success);
              break;
            }
            case 'd':
              banking.print();
              break;
            case 'q':
              Out.println("Beenden");
              break;
            default:
              Out.println("Ungültige Operation");
              break;
          }
        } while(op != 'q');
      }
     
      static void printMenu() {
        Out.println();
        Out.println("*********** Bankverwaltung ********");
        Out.println("Konto anlegen ................... a");
        Out.println("Einzahlen ....................... e");
        Out.println("Beheben ......................... b");
        Out.println("Überweisen ...................... t");
        Out.println("Übersicht drucken ............... d");
        Out.println("Beenden ......................... q");
        Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
      }
     
      static char readOperation() {
        char ch = Character.toLowerCase(In.readChar());
        In.readLine();
        return ch;
      }
     
      static void printTitle(String text) {
        Out.println("*** " + text + " ***");
      }
     
      static String getString(String text) {
        Out.print(text + ": ");
        return In.readLine();
      }
     
      static double getDouble(String text) {
        Out.print(text + ": ");
        return In.readDouble();
      }
     
      static int getInt(String text) {
        Out.print(text + ": ");
        return In.readInt();
      }
     
      static void printMessage(String operation, boolean success) {
        String message = success ?
          operation + " erfolgreich durchgeführt" :
          "Ungültige Operation";
        Out.println(message);
      }
    }

    Im getting this error:

    banking\Banking.java:25: error: <identifier> expected
    private Acount getAccount(accountNo) throws NoSuchAccountException {
    ^
    1 error

    Any help?

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    The ^ does not align with where the error was. Wrapping lines in code tags will preserve spacing. The ^ should be under accountNo.
    Banking.java:29: error: <identifier> expected
      private Acount getAccount(accountNo) throws NoSuchAccountException {
                                         ^
    What is wrong with that method declaration at the location above the ^? You have coded many methods declarations, what is different about this one?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    Yea the ^ was pointing to the wrong thing.Actually I've fixed the error.I was sussposed to give a type as a parameter (int accountNo). But now I'm facing a diffrent problem.

    This error;

    C:\Users\Hp\Desktop\ue9>javac banking/Banking.java
    banking\Banking.java:29: error: cannot find symbol
      return account;

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    error: cannot find symbol
    You left off the line(s) that give the symbol that can be found.
    TestCode26.java:363: error: cannot find symbol
          int x = that;
                  ^
      symbol:   variable that    <<<<<<<< This line is missing

    What is on line 29?
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    I've fixed the problem, this is how the code looks like, my return value was wrong.

     
      private Account getAccount(int accountNo) {
      if (accountNo >= accounts.length || accounts[accountNo] == null) {
       throw new NoSuchAccountException(accountNo);
      }
      return  accounts[nOfAccounts];
    }

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    Does the code execute correctly now? Do you get the expected results?
    If you don't understand my answer, don't ignore it, ask a question.

  14. #14
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    The code compiles without any errors I'll do some testing and I'll let you know!

  15. #15
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    Okay after quite a while I've managed to solve (at least I hope so) most of the errors in my code. But there is still this one error that I cannot solve.

     
    public boolean withdraw(int accountNo, double amount) throws OverdraftLimitReachedException {
        if (amount > 0.0) {
    		throw new OverdraftLimitReachedException(accountNo,amount,overdraft);
    	}
        Account account = accounts[accountNo];
        return account.withdraw(amount);

    It says it cannot find the simbol overdraft.I've tried adding it to the constructor as a parameter but than in the main method where I execute this method I get an error that the symbol cant be found.

    Here is the error

    banking\Banking.java:122: error: cannot find symbol
              boolean success = banking.withdraw(accountNo, amount,overdraft);
                                                                                                   ^
      symbol:   variable overdraft
      location: class Banking
    1 error
     
    C:\Users\Hp\Desktop\ue9>

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    symbol: variable overdraft
    Where is the variable: overdraft defined that is in scope where it is being used?
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    The overdraft variable is defined in class Account

     
    Account(int accountNo, Customer owner, double overdraft) {
        this.accountNo = accountNo;
        this.owner = owner;
        this.overdraft = overdraft;
      }
     
      void print() {
        Out.println("Kontonummer: " + accountNo);
        owner.print();
        Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n",
          balance, overdraft);
      }
     
      boolean deposit(double amount) {
        if (amount <= 0) return false;
     
        balance += amount;
        return true;
      }
     
      boolean withdraw(double amount) {
        if (amount <= 0 || !isCovered(amount)) return false;
     
        balance -= amount;
        return true;
      }
     
      boolean isCovered(double amount) {
        return amount - overdraft <= balance;
      }
     
      boolean transfer(Account target, double amount) {
        boolean success = withdraw(amount);
        if (!success) return false;
     
        target.deposit(amount);
        return true;
      }
    }

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    Is that in scope where it is being used that caused the error?

    Are you asking this question on other sites? Please post a link on both sites to the other site.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    I dont think I get your first question. "Is that in scope where it is being used that caused the error?" what exactly does that mean.Yes I am also asking on stackoverflow about the same issue

    Here is the link : https://stackoverflow.com/questions/...51592_62110285

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Putting an exception in an method

    what exactly does that mean.
    Did you google what "in scope" means?
    A simple example is anything defined within a {} pair is not in scope outside of the {}s
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Putting an exception in an method

    I have found a great website explaining scope (https://www.java-made-easy.com/variable-scope.html). I will read through this carefully and try to adapt my code.

Similar Threads

  1. Replies: 7
    Last Post: September 28th, 2014, 06:54 PM
  2. [SOLVED] null pointer exception error for a method calling a graphics obj help please
    By jorys22 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: December 2nd, 2013, 04:02 PM
  3. Help in putting actions to buttons
    By juliusmasa in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 14th, 2011, 07:22 AM
  4. Replies: 2
    Last Post: August 3rd, 2011, 11:13 AM
  5. Need help putting GUI in program!
    By greyfox175 in forum AWT / Java Swing
    Replies: 5
    Last Post: May 4th, 2011, 08:55 PM