Validation in ATM

2

The user starts by putting a name for the account and the starting balance, here already has a problem, I want you can not enter negative values or broken numbers

In the option deposit also I want to be able to enter negative numbers or broken numbers.

In the exact service that does not allow to enter the broken and negative numbers again, in the service if I type a negative number it adds up with the balance that has in the type account: I paid -1 and I have 10 of balance, the balance that is will have after the service and 11.

Class Caixa , where you enter the name and opening 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 depositing, withdrawing, and extracting actions:

    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");
        }
    }
}
    
asked by anonymous 14.12.2017 / 11:57

2 answers

2

You just need to add one more check on your draft method, you need to verify that the value reported by the client is less than 0

The ideal is to do the same to deposit it, the two methods will look 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");
    }
}
    
14.12.2017 / 12:12
2

tag wants it to be object oriented, right? Well, the code is far from OOP. I've improved, but it's still not ideal. Of course I solved the problem reported in the question.

I've changed some texts and names to get more into the correct context.

I took the random because accounts do not have random numbers but sequential numbers. It is true that for this code can only have one account, so it makes no difference, but if it is changed to have multiple accounts already ready.

I took every screen part of class Conta . This is OO. Mixing responsibilities is not. Probably the specific screen operations should be in another class, but do not need 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 has been validated in the basics as this response . If you do not want a value with decimal part, do not use a type that allows decimal.

If you want to use a type with a decimal part, do not use double .

It seems to me that the verification can be taken, 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's not worth doing something more complex.

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

Do not forget that you still have several less obvious errors in the code, but nothing so serious. In actual production code, you'd have to do a lot more than that. There is something that I could have done better, but I was getting tired, this has given way to 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;
    }
}

See running on ideone . And no Coding Ground . Also I placed in GitHub for future reference .

    
14.12.2017 / 16:59