Repeat loop while user choose option to continue

Asked

Viewed 154 times

1

I am developing an application in Java and after calculating everything the user asked, I need it to inform the following message: "Deseja calcular novamente? S/N".

I’m using the do/while but I’m not getting it to work. Below is the code:

package beta;

import java.util.Scanner;

/**
 *
 * @author lab
 */
public class Beta {

    public static void main(String[] args) {

        Scanner obj = new Scanner(System.in);
        String escolha ;
        double raio , area , base , altura , raioM , diagonalm , diagonalM ;
        String volta;
        Scanner scanner = new Scanner(System.in);


        do{

            System.out.println("O que deseja Calcular? ");
                    System.out.println("1. Circulo");
                    System.out.println("2. Triângulo");
                    System.out.println("3. Trapézio");
                    System.out.println("4. Retângulo");
                    System.out.println("5. Corda Circular");
                    System.out.println("6. Diagonal do Losango");
                    System.out.println("7. Sair");
            escolha = obj.nextLine();


switch(escolha){

             case "1":
                System.out.println("Qual o raio do Círculo? ");
                raio = obj.nextDouble();
                area = 3.14 * (raio*raio);
                System.out.println("A área do Círculo é " + area);
             break;

             case "2":
                System.out.println("Qual a base do Triângulo: ");
                base = obj.nextDouble();
                System.out.println("Qual a Altura do Triângulo: ");
                altura = obj.nextDouble();
                area = (base*altura)/2;
                System.out.println("A área do Triângulo é " + area);
             break;

             case "3":
                System.out.println("Qual a base do Trapézio: ");
                base = obj.nextDouble();
                System.out.println("Qual a Altura do Trapézio: ");
                altura = obj.nextDouble();
                area = (base+base)*altura/2;
                System.out.println("A área do Trapézio é " + area);
             break;
             case "4":
                System.out.println("Qual a base do Retângulo: ");
                base = obj.nextDouble();
                System.out.println("Qual a Altura do Retângulo: ");
                altura = obj.nextDouble();
                area = base*altura;
                System.out.println("A área do Retângulo é " + area);
             break; 
             case "5":
                System.out.println("Qual o maior raio da Corda Circular: ");
                raio = obj.nextDouble();
                System.out.println("Qual o menor raio da Corda Circular: ");
                raioM = obj.nextDouble();
                area = raio*raio - raioM*raioM;
                System.out.println("A área da corda circular é Pi " + area);
             break;
             case "6":
                System.out.println("Qual a maior Diagonal do Losango: ");
                diagonalM = obj.nextDouble();
                System.out.println("Qual a menor Diagonal do Losango: ");
                diagonalm = obj.nextDouble();
                area = (diagonalM*diagonalm)/2;
                System.out.println("A área do Losango é " + area);
             break;                          

           }   
      escolha = scanner.next();     
    } while(escolha.equalsIgnoreCase("Deseja calcular novamente? S/N"));            

    } // fim main

} // fim classe
  • 2

    You’re asking if what was read is identical to "Deseja calcular novamente? S/N" (ignoring high/low box difference), which makes no sense

2 answers

2


First, there’s no need to create two Scanner's, since both are reading from System.in. Using just one is enough (and calling one of them obj doesn’t help much, give better names for variables).

Another point is that the escolha should be compared with "s", and not with the text "Deseja calcular novamente? S/N".

Another detail is that methods like nextDouble() do not consume line break (in this case, the ENTER), then you should call nextLine() soon after, otherwise the next call from nextLine() will consume only the line break, leaving the escolha empty.

Missed also check if the option is "7", and exit the while in this case. I also removed the variable volta, because it is not used in the code.

Anyway, the code would look like this:

Scanner scanner = new Scanner(System.in);
String escolha;
double raio, area, base, altura, raioM, diagonalm, diagonalM;

do {
    System.out.println("O que deseja Calcular? ");
    System.out.println("1. Circulo");
    System.out.println("2. Triângulo");
    System.out.println("3. Trapézio");
    System.out.println("4. Retângulo");
    System.out.println("5. Corda Circular");
    System.out.println("6. Diagonal do Losango");
    System.out.println("7. Sair");
    escolha = scanner.nextLine();
    // se for 7, sai do while
    if ("7".equals(escolha))
        break;

    switch (escolha) {
        case "1":
            System.out.println("Qual o raio do Círculo? ");
            raio = scanner.nextDouble(); // use o "scanner", não mais o "obj"
         .... dentro do switch é igual
    }

    scanner.nextLine(); // consumir a quebra de linha, pois nextDouble() não a consome
    System.out.println("Deseja calcular novamente? S/N");
} while (scanner.nextLine().equalsIgnoreCase("s")); // nem precisa guardar o resultado de nextLine() em uma variável, pode comparar direto

But if the options can only be numbers, then why not use nextInt() to read them?

Scanner scanner = new Scanner(System.in);
int escolha;
double raio, area, base, altura, raioM, diagonalm, diagonalM;

do {
    System.out.println("O que deseja Calcular? ");
    System.out.println("1. Circulo");
    System.out.println("2. Triângulo");
    System.out.println("3. Trapézio");
    System.out.println("4. Retângulo");
    System.out.println("5. Corda Circular");
    System.out.println("6. Diagonal do Losango");
    System.out.println("7. Sair");
    escolha = scanner.nextInt();
    if (escolha == 7)
        break;

    switch (escolha) {
        case 1:
           ....

        case 2:
           ....

           ....etc

        default: // pequena "firula"
            System.out.printf("Opçao inválida: %d\n", escolha);
    }

    scanner.nextLine();
    System.out.println("Deseja calcular novamente? S/N");
} while (scanner.nextLine().equalsIgnoreCase("s"));
  • I was commenting at the time you posted the reply ;-)

  • @Jeffersonquesado And I was going to comment that I was responding at the time you commented :-)

  • And I was answering, I went out to dinner, I came back, I answered and I saw that you were already commenting on this answer =(

  • I made all the changes you indicated friend and was exactly as I wanted, thank you very much, I could not bear to break my head with this code anymore, I’m beginner in Java yet! kkk Thanks!

  • @Luísfillipemagalhães If one of the answers solved your problem, you can choose the one that best solved it and accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.

0

You can kill this charade by looking at the condition of the while, in your condition "(choice.equalsIgnoreCase("Do you want to calculate again? S/N");" you are comparing if the user wrote "Do you want to calculate again? S/N" ignoring the size of the letters, that is, to present the menu again at the end of one of its options (considering that the user has typed a number in the range [1,7]) the user would have to type "Want to calculate again? S/N".

Probably what you want can be done by swapping

escolha = scanner.next();     
} while(escolha.equalsIgnoreCase("Deseja calcular novamente? S/N")); 

for

System.out.println("Deseja calcular novamente? S/N");
escolha = scanner.next();  

} while(escolha.equalsIgnoreCase("s")); 

Obs: There are passages in your code that can be improved, I tried to focus only on the core of the question.

  • 1

    I will now test the program with the modifications, on the improvements in other excerpts, I’m beginner in java still kkkk less than 2 weeks learning, but I’ve quite liked the language!

  • Your tip was very helpful friend, but I’m still with a problem, after performing the calculations, the progamma suggests the question "Do you want to calculate again? S/N" as planned, but when I select the "S" it presents me the options again but before I answer what I want to calculate it already asks me the question "Want to calculate again? S/N" again.. Any idea how to fix this? But thank you so much for helping me out already!

  • To solve this problem you must change choice = obj.nextLine(); for choice = obj.next();, however it would be better if you already used nextInt() and switched switch cases to integer as well as @hkotsubo exemplified. I appreciate you being helpful =)

Browser other questions tagged

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