My calculator from the while in position 2, skips the insertion of the first value someone can help me?

Asked

Viewed 97 times

-5

package Calculadora;

import java.util.InputMismatchException;
import java.util.Scanner;

public class calculadora {
  public static void main(String[] args) {
    float valor1 = 0;
    float valor2 = 0;
    float opcao = 5;
    float resultado;
    //boolean loop = true;

    System.out.println("-Seja bem-vindo(a) a sua calculadora-");
    System.out.println("Escolha uma o por favor!!");
    System.out.println("1. Soma");
    System.out.println("2. Subtracao");
    System.out.println("3. Multiplicacao");
    System.out.println("4. Divisao");
    System.out.println("0. Sair");
    System.out.println("Operação: ");

    Scanner teclado = new Scanner(System.in);
    opcao = teclado.nextFloat();
    clearBuffet(teclado);

    while (opcao != 0) {
      if (opcao == 1) {
        System.out.print("Digite o primeiro valor: ");
        clearBuffet(teclado);

        try {
          valor1 = teclado.nextFloat();
          clearBuffet(teclado);
        } catch (InputMismatchException e) {
          System.out.print("Vamos começar denovo, digite apenas números\n\n");
          clearBuffet(teclado);
          continue;
        }
      }
      System.out.print("Digite o segundo valor: ");
      try {
        valor2 = teclado.nextFloat();
        clearBuffet(teclado);
        break;
      } catch (InputMismatchException e) {
        System.out.print("Vamos começar denovo, digite apenas números\n\n");
        clearBuffet(teclado);
        continue;
      }
    }

    resultado = valor1 + valor2;
    System.out.println(resultado);

    while (opcao != 0) {
      if (opcao == 2) {
        System.out.print("Digite o primeiro valor: ");
        clearBuffet(teclado);

        try {
          valor1 = teclado.nextFloat();
          clearBuffet(teclado);
        } catch (InputMismatchException e) {
          System.out.print("Vamos começar denovo, digite apenas números\n\n");
          clearBuffet(teclado);
          continue;
        }

        System.out.print("Digite o segundo valor: ");
        clearBuffet(teclado);
        try {
          valor2 = teclado.nextFloat();
          clearBuffet(teclado);
          break;
        } catch (InputMismatchException e) {
          System.out.print("Vamos começar denovo, digite apenas números\n\n");
          clearBuffet(teclado);
          continue;
        }
      }
    }
    resultado = valor1 - valor2;
    System.out.print(resultado);

    while (opcao != 0) {
      if (opcao == 3) {
        System.out.print("Digite o primeiro valor: ");
        clearBuffet(teclado);
        try {
          valor1 = teclado.nextFloat();
        } catch (InputMismatchException e) {
          System.out.print("Vamos começar denovo, digite apenas números\n\n");
          clearBuffet(teclado);
          continue;
        }

        System.out.print("Digite o segundo valor: ");
        clearBuffet(teclado);

        try {
          valor2 = teclado.nextFloat();
          break;
        } catch (InputMismatchException e) {
          System.out.print("Vamos começar denovo, digite apenas números\n\n");
          clearBuffet(teclado);
          continue;
        }
      }

    }

    resultado = valor1 * valor2;
    System.out.print(resultado);

    while (opcao != 0) {
      if (opcao == 4) {
        if (opcao == 1) {
          System.out.print("Digite o primeiro valor: ");
          clearBuffet(teclado);

          try {
            valor1 = teclado.nextFloat();
          } catch (InputMismatchException e) {
            System.out.print("Vamos começar denovo, digite apenas números\n\n");
            clearBuffet(teclado);
            continue;
          }

          System.out.print("Digite o segundo valor: ");
          clearBuffet(teclado);

          try {
            valor2 = teclado.nextFloat();
            break;
          } catch (InputMismatchException e) {
            System.out.print("Vamos começar denovo, digite apenas números\n\n");
            clearBuffet(teclado);
            continue;
          }
        }
      } else if (valor2 == 0) {
        System.out.println("Impossivel dividir por 0!!");

      } else resultado = valor1 / valor2;
      System.out.print(resultado);

      if (opcao >= 5) {
        System.out.println("Opção invalida");

      }
    }
  }

  private static void clearBuffet(Scanner scanner) {
    // TODO Auto-generated method stub
    if (scanner.hasNextLine()) {
      scanner.nextLine();
    }
  }
}
  • Just to state that the statement of the answer below, that a method must have at most 15 lines, is mistaken and absurd. Anyone who tries to define a "magic" number of lines that is "right" for all cases is automatically wrong, because it depends a lot on the context. To learn more about the subject, I suggest you read here and here

  • Just to leave a suggestion instead of trying to clean the buffer (it’s not bufft), you can simply read the whole line and try to convert it to number, like this: https://ideone.com/XNOA0p. (to read from the keyboard it is better to understand the reasons by reading the link already quoted). Also note that I deleted this unnecessary loop pile, and it only does the operation that was chosen in the menu (in addition the answer below suggests creating the Scanner every hour within the method lerOpcao, which is unnecessary). Anyway, I could improve more, but in general lines would be this.

2 answers

-1

I believe it’s because of the method clearBuffet(Scanner). He jumps to the next line: scanner.nextLine();.

-5


The code is long, so pouco legível, what is normal when we are doing the work having little experience. It is part of learning.

My suggestion even to make it easier to find any possible error, is dividir o código em métodos.

I suggest that the code be divided into smaller methods, where each will be defined for a specific function. A few reasons for this:

  • The concept of what the method does is easily understood and defined in our mind
  • The reading of a method can be done on the screen without scrolling the page
  • Finding an error in the problem as a whole gets much easier
  • Maintenance (future changes) of codes with small methods becomes much easier and faster

That said, I’ll just start writing a code of what you need and you can keep doing so... with small methods being called. For example:

static void iniciarCalculadora() {
    System.out.println("-Seja bem-vindo(a) a sua calculadora-");
    System.out.println("Escolha uma o por favor!!");
    System.out.println("1. Soma");  
    System.out.println("2. Subtracao");  
    System.out.println("3. Multiplicacao");  
    System.out.println("4. Divisao");  
    System.out.println("0. Sair");  
    System.out.println("Operação: "); 
}

public static void main(String[] args) {
    iniciarCalculadora();
    int opcao = lerOpcao();
}

static int lerOpcao() {
    Scanner teclado = new Scanner(System.in);
    int opcao = teclado.nextInt();
    clearBuffet(teclado);
    return opcao;
}

private static void clearBuffet(Scanner scanner) {
    if (scanner.hasNextLine()) {
        scanner.nextLine();
    }
}

This is just the beginning of the work done this different way, with small methods solving every part of the problem.

My suggestion is this. You redo, and later post here with pequenos métodos and he stays mais legível, then we can see much easier if there is a bug.

  • 3

    A method is not easily understood because it has 5 to 15 lines. Method with other sizes fit on the screen without scrolling the page except with many dozens of lines. Finding an error is easier for several reasons and not because it has 5 to 15 lines, it can be easier with less than 5 lines, and if well done it can be more than 15 lines. Same goes for maintenance. Who counts lines to define quality of a method does not know how to program and clings to formulas to pretend it is well done. Quality is given by deeply studying and applying logical reasoning.

  • 3

    Divide properly is good, count lines is not.

  • It’s not about counting lines to define quality. However, a method with so many lines can generate numerous outputs, be little or not reusable. Only the line count does not make sense. But how to have cohesion in methods? With a well defined function for him or with him doing everything? The author by the type of problem presented is in the learning phase. I think this concept would be useful for him. Anyone who has ever maintained code in any company knows how painful it is to take long codes to look for bugs.

  • 1

    The problem is to hit "magic numbers" (5 to 15 lines, but it could be any other values that the problem would remain the same) and say that it is because of these numbers that you get all the advantages you mention. You can get these same advantages with different values (20 to 30? 10 to 40? ), and this varies and depends a lot on the context. There are no absolute values that work for any case, and trying to nail such values is the main problem being criticized here. Related reading (and recommended): here and here

  • 1

    In fact, it is precisely by the author of the question - apparently - being in the learning phase that we are warning here, because this type of thinking ("methods can only have at most x lines", X being a fixed value of any) is harmful and ends up creating addictions difficult to take away later. It would be much better to teach that it depends on the context and there is a magic number of lines that is ideal for all cases (which is the discussion of the links I indicated above). I agree that the ideal is that they are not too long (but the "too much" is relative, and will not always be exactly "15 lines").

  • I edited the answer taking the idea about the ideal number of lines. Because the idea was to present the concept of cohesion. You can remove the answer if you think it adds nothing to learning. I appreciate the reading instructions.

Show 1 more comment

Browser other questions tagged

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