#How to write general code in Java

7 messages · Page 1 of 1 (latest)

modest panther
#

I am having some issues with a code I'm writing, the teacher asked me to simplify the code and turn it into a general thing that would apply for two different variables. The code asks for a deposit input, then adds the deposit to each different account. Here's the code for the class I'm doing it on:

public class AccountTest 
{
    public static void main(String[] args) 
    {
    Account account1 = new Account("Jane Green", 50.00);
    Account account2 = new Account("John Blue", -7.53);

    System.out.printf("Nome do Account1 é %s%n", account1.getName());
    System.out.printf("Nome do Account2 é %s%n", account2.getName());
    System.out.printf("%s balanço: $%.2f %n", account1.getName(), account1.getBalance());
    System.out.printf("%s balanço: $%.2f %n", account2.getName(), account2.getBalance());*/
        
    Scanner input = new Scanner(System.in);
        
    System.out.print("Entre com o depósito para account1:");
    double depositAmount = input.nextDouble();
    System.out.printf("%nAdicionando %.2f para o balanço da account1%n%n", depositAmount);
    account1.deposit(depositAmount);
        
    System.out.printf("%s balanço: $%.2f %n", account1.getName(), account1.getBalance());
    System.out.printf("%s balanço: $%.2f %n", account2.getName(), account2.getBalance());
        
    System.out.print("Entre com o depósito para account2:");
    depositAmount = input.nextDouble();
    System.out.printf("%nAdicionando %.2f para o balanço da account2%n%n", depositAmount);
    account2.deposit(depositAmount);
        
    System.out.printf("%s balanço: $%.2f %n", account1.getName(), account1.getBalance());
    System.out.printf("%s balanço: $%.2f %n", account2.getName(), account2.getBalance());
  }
}```
#

The thing I'm stuck on is how to have each variable have its own value deposited without having to call both of them

drifting frigate
#

Create a function that you can pass an account to. That function then has all the logic

modest panther
#

Would you have an example of that?

#

Also does it make any difference if I put the function before or after the main?

old bobcat
paper quartz
#

use a method