Validation in an ATM

Asked

Viewed 519 times

2

The user starts by putting a name to the account and the initial balance, here already has a problem, I want it is not possible to enter negative values or broken numbers

In the deposit option I also want to make it impossible to type negative numbers or broken numbers.

No serve precise do not let enter the broken and negative numbers again, no serve if I enter a negative number it adds with the balance you have in the account type: I drew -1 and I have 10 balance, the balance you will have after the serve and 11.

Class Caixa, where you enter the initial name and balance:

import java.util.Scanner;
import java.util.Random;

public class Caixa {


    public static void main(String[] args){
        // Declarando as variáveis, Scanner e Random
        String nome;
        double inicial;
        Scanner entrada = new Scanner(System.in);
        Random numero = new Random();
        int conta = 1 + numero.nextInt(9999);

        //Obtendo os dados iniciais do Cliente
        System.out.println("Cadastrando novo cliente.");
        System.out.print("Ente com seu nome: ");
        nome = entrada.nextLine();

        System.out.print("Entre com o valor inicial depositado na conta: ");
        inicial = entrada.nextDouble();

        //Criando a conta de um cliente
        Conta minhaConta = new Conta(nome, conta, inicial);
        minhaConta.iniciar();
    }


}

Class Conta, performs the actions of depositing, withdrawing and extract:

    import java.util.Scanner;

public class Conta {
    private String nome;
    private int conta, saques;
    private double saldo;
    Scanner entrada = new Scanner(System.in);

    public Conta(String nome, int conta, double saldo_inicial){
        this.nome=nome;
        this.conta=conta;
        saldo=saldo_inicial;
        saques=0;
    }

    public void extrato(){
        System.out.println("\tEXTRATO");
        System.out.println("Nome: " + this.nome);
        System.out.println("Número da conta: " + this.conta);
        System.out.printf("Saldo atual: %.2f\n",this.saldo);
        System.out.println("Saques realizados hoje: " + this.saques + "\n");

    }

    public void sacar(double valor){
        if(saldo >= valor){
            saldo -= valor;
            saques++;
            System.out.println("Sacado: " + valor);
            System.out.println("Novo saldo: " + saldo + "\n");
        } else {
            System.out.println("Saldo insuficiente. Faça um depósito\n");
        }
    }

    public void depositar(double valor)
    {
        saldo += valor;
        System.out.println("Depositado: " + valor);
        System.out.println("Novo saldo: " + saldo + "\n");
    }

    public void iniciar(){
        int opcao;

        do{
            exibeMenu();
            opcao = entrada.nextInt();
            escolheOpcao(opcao);
        }while(opcao!=4);
    }

    public void exibeMenu(){

        System.out.println("\t Escolha a opção desejada");
        System.out.println("1 - Consultar Extrato");
        System.out.println("2 - Sacar");
        System.out.println("3 - Depositar");
        System.out.println("4 - Sair\n");
        System.out.print("Opção: ");

    }

    public void escolheOpcao(int opcao){
        double valor;

        switch( opcao ){
            case 1:    
                    extrato();
                    break;
            case 2: 
                    if(saques<3){
                        System.out.print("Quanto deseja sacar: ");
                        valor = entrada.nextDouble();
                        sacar(valor);
                    } else{
                        System.out.println("Limite de saques diários atingidos.\n");
                    }
                    break;

            case 3:
                    System.out.print("Quanto deseja depositar: ");
                    valor = entrada.nextDouble();
                    depositar(valor);
                    break;

            case 4: 
                    System.out.println("Sistema encerrado.");
                    break;

            default:
                    System.out.println("Opção inválida");
        }
    }
}

2 answers

2

For tag You want it to be object-oriented, right? Well, the code is far from OOP. I’ve improved it, but it’s not ideal yet. And of course I solved the problem reported in the question.

I changed some texts and names to stay more within the correct context.

I took out random because accounts don’t have random numbers, they have sequential numbers. It is true that by this code can only have one account, so it makes no difference, but if it is changed to have several accounts is already ready.

I took out all the canvas of the class Conta. This is the OO. Mixing responsibilities isn’t. Probably the specific screen operations should be in another class, but it doesn’t need in something so simple.

I could let you do it the "wrong" way, but it looks like you want to learn the right thing.

The data entry was validated in the basic according that answer. If you do not want a decimal part value, do not use a decimal type.

If you want to use a decimal part type, don’t use the double.

It seems to me that the check can be drawn, if the value is accepted, how to generate the account number should belong to Conta. In fact it should be up to another mechanism, but for an exercise it is not worth doing something more complex.

The right thing would be to use Enum or something similar to communicate the problem when trying the operation, but I’m lazy :) You have to think it should be by exception, there is this culture in Java, I abhor exceptions unless they are the best mechanism, which is not the case.

Do not forget that there are still several less obvious errors in the code, but nothing so serious. In real code in production would need to do much more than that. There are things I could have done better, but I was tired, it was exhausting a technical detail.

import java.util.Scanner;

public class Caixa {
    static private Conta minhaConta;
    static private Scanner entrada = new Scanner(System.in);
    public static void main(String[] args) {
        int opcao = -1;
        do {
            System.out.println("\t Escolha a opção desejada");
            if (minhaConta != null) {
                System.out.println("1 - Consultar Saldo");
                System.out.println("2 - Sacar");
                System.out.println("3 - Depositar");
            }
            System.out.println("4 - Abrir Conta");
            System.out.println("0 - Sair\n");
            System.out.print("Opção: ");
            opcao = lerInt();
            if (minhaConta == null && opcao != 0) opcao = 4;
            switch (opcao) {
            case 1:
                System.out.println("SALDO");
                System.out.println("Nome: " + minhaConta.getNome());
                System.out.println("Número da conta: " + minhaConta.getConta());
                System.out.printf("Saldo atual: %.2f\n", minhaConta.getSaldo());
                System.out.println("Saques realizados: " + minhaConta.getSaques() + "\n");
                break;
            case 2:
                if (minhaConta.podeSacar()) {
                    System.out.print("Quanto deseja sacar: ");
                    int ok = minhaConta.sacar(lerInt());
                    if (ok >= 0) {
                        System.out.println("Sacado: " + ok);
                        System.out.println("Novo saldo: " + minhaConta.getSaldo() + "\n");
                    } else if (ok == -1) System.out.println("Não pode ser negativo\n");
                    else if (ok == -2) System.out.println("Saldo insuficiente. Faça um depósito\n");
                     else if (ok == -3) System.out.println("Limite de saques atingidos.\n");
                } else System.out.println("Limite de saques atingidos.\n");
                break;
            case 3:
                System.out.print("Quanto deseja depositar: ");
                int ok = minhaConta.depositar(lerInt());
                if (ok >= 0) {
                    System.out.println("Depositado: " + ok);
                    System.out.println("Novo saldo: " + minhaConta.getSaldo() + "\n");
                } else System.out.print("Não pode ser negativo");
                break;
            case 4: 
                System.out.println("Cadastrando novo cliente.");
                System.out.print("Ente com seu nome: ");
                System.out.print("Entre com o valor inicial depositado na conta: ");
                minhaConta = new Conta(entrada.nextLine(), lerInt());
                break;
            case 0: break;
            default:
                System.out.println("Opção inválida");
            }
        } while (opcao != 0);
    }
    private static int lerInt() {
        while (true) {
            String lido = entrada.nextLine().trim();
            try {
                return Integer.parseInt(lido);
            } catch (NumberFormatException e) {
                System.out.println("Desculpe, mas " + lido + " não é um número inteiro. Tente novamente.");
            }
        }
    }
}

class Conta {
    static private int ultimaConta;
    private String nome;
    private int conta, saques;
    private double saldo;
    public String getNome() { return nome; }
    public double getConta() { return conta; }
    public double getSaldo() { return saldo; }
    public int getSaques() { return saques; }
    public boolean podeSacar() { return saques < 3; }
    public Conta(String nome, int saldoInicial) {
        this.nome = nome;
        conta = ++ultimaConta;
        saldo = saldoInicial < 0 ? 0 : saldoInicial;
    }
    public int sacar(int valor) {
        if (valor < 1) return -1;
        if (saldo < valor) return -2;
        if (!podeSacar()) return -3;
        saldo -= valor;
        saques++;
        return valor;
    }
    public int depositar(int valor) {
        if (valor < 1) return -1;
        saldo += valor;
        return valor;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

2


You just need to add one more check to your withdraw method, you need to check if the value reported by the customer is less than 0

The ideal is to do the same to deposit it, the two methods will stay like this:

public void sacar(double valor){
    if(valor < 0){
      System.out.println("Não é possível sacar um valor negativo!\n");
    }
    else
    {
      if(saldo >= valor){
          saldo -= valor;
          saques++;
          System.out.println("Sacado: " + valor);
          System.out.println("Novo saldo: " + saldo + "\n");
      } else {
          System.out.println("Saldo insuficiente. Faça um depósito\n");
      }
    }
}

public void depositar(double valor)
{
    if(valor < 0){
      System.out.println("Não é possível depositar um valor negativo!\n");
    }
    else
    {
      saldo += valor;
      System.out.println("Depositado: " + valor);
      System.out.println("Novo saldo: " + saldo + "\n");
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.