Return to start if size is not reached

Asked

Viewed 281 times

1

Guys, I got this week a really fucked-up college job and I’m having a problem with a part of it... The thing is, I have to set up a system for a bracelet store, which gives the choice of size and pendants, each pendant and size with its length and price. So far what I learned was the basics of JAVA so the difficulty of assembling this system. However I managed to calm down, I’m only in trouble that I do not know how to make him repeat the parts of choice of pendant, in case the total size of pendant that the user choose does not close the size of the bracelet.. The code is heavily polluted by the fact that this is the knowledge that I have at the moment... If anyone has balls and tells me how to do I’m waiting. Hugs!

import java.util.Scanner;
public class Bichara_System{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.println("Digite o tamanho da pulseira\nPequena (17cm) - R$180,00\nMédia (18cm) - R$200,00\nGrande (20cm) - R$240,00");
        String pulseira = in.nextLine();
        int valorpulseira = 0;
        int tamanhopulseira = 0;
        if(pulseira.toLowerCase().equals("pequena")){
            pulseira = "pequena";
            valorpulseira = 180;
            tamanhopulseira = 17;
            System.out.println("Total: R$180,00\nAgora escolha o pingente:");
        } else if(pulseira.toLowerCase().equals("media")){
            pulseira = "media";
            valorpulseira = 200;
            tamanhopulseira = 18;
            System.out.println("Total: R$200,00\nAgora escolha o pingente:");
        } else if(pulseira.toLowerCase().equals("grande")){
            pulseira = "grande";
            valorpulseira = 240;
            tamanhopulseira = 20;
            System.out.println("Total: R$240,00\nAgora escolha o pingente:");
        }
        System.out.println("Bichinhos (1,3cm) - R$225,00\nBonequinhos (1,5cm) - R$185,00\nBerloques (0,5cm) - R$200,00\nCubinhos (1cm) - R$190,00\nRolinho (2cm) - Prata, Pedra e Esmaltados.");
        String pingente = in.nextLine();
        int valorpingente = 0;
        double tamanhopingente = 0;
        int valor = 0;
        double tamanhofinal = 0;
        if(pingente.toLowerCase().equals("bichinhos")){
            pingente = "bichinhos";
            valorpingente = 225;
            tamanhopingente = 1.3;
            System.out.println("Quantos?");
            int qntsbichinhos = in.nextInt();
            double tamanhobichinhos = qntsbichinhos*tamanhopingente;
            if(tamanhobichinhos > tamanhopulseira){
                System.out.println("Você escolheu um número de bichinhos que excede o tamanho da pulseira!");
            } else {
                int valorbichinhos = qntsbichinhos*valorpingente;
                valor = valorpulseira+valorbichinhos;
                tamanhofinal = qntsbichinhos*tamanhopingente+tamanhopulseira;
                System.out.println("\nTotal:" +valor);
            }
        }
        double tamanhofinal2 = 0;
        if(pingente.toLowerCase().equals("bonequinhos")){
            pingente = "bonequinhos";
            valorpingente = 185;
            tamanhopingente = 1.5;
            System.out.println("Quantos?");
            int qntsbonequinhos = in.nextInt();
            double tamanhobonequinhos = qntsbonequinhos*tamanhopingente;
            if(tamanhobonequinhos > tamanhopulseira){
                System.out.println("Você escolheu um número de bonequinhos que excede o tamanho da pulseira!");
            } else {
                int valorbonequinhos = qntsbonequinhos*valorpingente;
                valor = valorpulseira+valorbonequinhos;
                tamanhofinal2 = qntsbonequinhos*tamanhopingente+tamanhopulseira;
                System.out.println("\nTotal:" +valor);
            }
        }
        double tamanhofinal3 = 0;
        if(pingente.toLowerCase().equals("berloques")){
            pingente = "berloques";
            valorpingente = 200;
            tamanhopingente = 0.5;
            System.out.println("Quantos?");
            int qntsberloques = in.nextInt();
            double tamanhoberloques = qntsberloques*tamanhopingente;
            if(tamanhoberloques > tamanhopulseira){
                System.out.println("Você escolheu um número de berloques que excede o tamanho da pulseira!");
            } else {
                int valorberloques = qntsberloques*valorpingente;
                valor = valorpulseira+valorberloques;
                tamanhofinal3 = qntsberloques*tamanhopingente+tamanhopulseira;
                System.out.println("\nTotal:" +valor);
            }
        }
        double tamanhofinal4 = 0;
        if(pingente.toLowerCase().equals("cubinhos")){
            pingente = "cubinhos";
            valorpingente = 190;
            tamanhopingente = 1;
            System.out.println("Quantos?");
            int qntscubinhos = in.nextInt();
            double tamanhocubinhos = qntscubinhos*tamanhopingente;
            if(tamanhocubinhos > tamanhopulseira){
                System.out.println("Você escolheu um número de cubinhos que excede o tamanho da pulseira!");
            } else {
                int valorcubinhos = qntscubinhos*valorpingente;
                valor = valorpulseira+valorcubinhos;
                tamanhofinal4 = qntscubinhos*tamanhopingente+tamanhopulseira;
                System.out.println("\nTotal:" +valor);
            }
        }
        double tamanhofinal5 = 0;
        if(pingente.toLowerCase().equals("rolinho")){
            pingente = "rolinho";
            tamanhopingente = 2;
            System.out.println("Escolha o material:\nPrata - R$150,00\nPedras - R$220,00\nEsmaltados - R$198,00");
            String rolinho = in.nextLine();
            if(rolinho.toLowerCase().equals("prata")){
                valorpingente = 150;
            }if(rolinho.toLowerCase().equals("pedras")){
                valorpingente = 220;
            }if(rolinho.toLowerCase().equals("esmaltados")){
                valorpingente = 198;
            }
            System.out.println("Quantos?");
            int qntsrolinhos = in.nextInt();
            double tamanhorolinhos = qntsrolinhos*tamanhopingente;
            if(tamanhorolinhos > tamanhopulseira){
                System.out.println("Você escolheu um número de rolinhos que excede o tamanho da pulseira!");
            } else {
                int valorcubinhos = qntsrolinhos*valorpingente;
                valor = valorpulseira+valorcubinhos;
                tamanhofinal4 = qntsrolinhos*tamanhopingente+tamanhopulseira;
                System.out.println("\nTotal:" +valor);
            }
        }
        System.out.println("Você deseja adquirir um suporte de segurança pelo preço de R$95,00? (Sim ou Não)");
        String suporte = in.nextLine();
        int valorsuporte = 0;
        if(suporte.toLowerCase().equals("sim")){
            valorsuporte = 95;
            valor = valorpulseira+valorpingente+valorsuporte;
            System.out.println("Total: "+valor);
        } else {
            valor = valorpulseira+valorpingente+valorsuporte;
            System.out.println("Total: "+valor);
        }

    }
}
  • 1

    I gave a identada in the code to make it easier to read, if I’ve harmed anything without wanting to please reverse the edit, ok?

  • Okay, anything I revert xD

  • 1

    Start by breaking your code into smaller methods. escolherPulseira, escolherPingente, checaTamanho, escolherMaterial, adquirirSuporte, etc. If you have ever taken object orientation classes it is interesting to create model classes as well (Pulseira, Pingente, etc.).

  • 2

    In possession of methods like this you can do something like do {montaPulseira(pulseira, bichinhos);} while (pulseira.getTamanho() > tamanhoPulseira).

  • Well, then, I haven’t had any lessons about it yet! I could even pick up and learn by seeing examples on Iternet but I have to do the work with what was worked in class. I believe that this teacher is a little clueless to have such a system made only using ifs and Switchs and methods to declare variables... I wanted to do something like if(TamanhoTotalComPingentes < tamanhoDaPulseiraEscolhida{ refaz o processo de escolha de pingente armazenando o tamanho e o preço do ja escolhido}

  • 1

    William, what you’re wanting to do is a goto (which does not exist in Java). The best Ness option in this case is to break in methods. If you can’t do that (I would, your teacher won’t cash note for doing the code the right way) you can surround the entire piece of assembly with a while (tamanhoPingentes < tamanhoDaPulseiraEscolhida), so it only exits the loop when the user has chosen a valid combination.

  • ta but using the while it will continue with the data that are already stored??

  • Yes if you declare the variable outside the loop scope.

  • Perfect then. However I don’t know how to break into methods :/ Have any link to pass me? then in case I have more problems I ask another question..

  • What about loops, was that seen in class? No loops and no recursion (either) this repetition you want is impossible (unless you copy and paste your code N times... baita gambiarra...)

  • exactly would be a hell of a stunt.. I just found out that I can use while, so I think I’ll opt for the option of breaking into methods and using while. To do this, besides breaking the code into methods, just remove the variable definitions from within the IFS and leave it in the correct main function?

  • 1

    @Guilherme Você não accurate break into methods to use while - It would only be a question of organization, but since your code is essentially sequential, I don’t see any big problems in having a single giant function. Let me give you an example in response.

  • @William Ready! I would also add that - if you were to break into methods, you would also have to pass parameters and receive a return value, or maybe create fields (probably static) to share data between the main and the other functions. Eventually you will learn all this, but it is not necessary to run over things... Splitting your code into sections already helps a lot, like /* Escolha da pulseira */ código /* Escolha do tipo do pingente */ mais código /* Adquirir suporte */ mais código

  • Hello @Guilherme, just adding what the noble friends have already said, it would be good for you to take a look at Object Orientation, as support material here I leave the link to the excellent booklet of Caelum: https://www.caelum.com.br/apostila-java-orientacao-objetos/

Show 9 more comments

2 answers

4


If you want to execute certain code, then repeat it if at the end certain condition is not satisfied, the most natural way is using a do...while (do X, if condition Y is true do X again, etc). But it is also possible using a simple while (if condition Y is true do X, if condition Y is true do X again, etc).

  1. Move everything that can be repeated into a separate "section". For example, your code:

    System.out.println("Total: R$180,00\nAgora escolha o pingente:");
    

    is problematic because that way the Agora escolha o pingente: will only be printed once (in addition this phrase repeats several times, it would be better to separate it anyway). An alternative would be:

    if(pulseira.toLowerCase().equals("pequena")){
        pulseira = "pequena";
        valorpulseira = 180;
        tamanhopulseira = 17;
        System.out.println("Total: R$180,00\n");
    } else if(pulseira.toLowerCase().equals("media")){
        pulseira = "media";
        valorpulseira = 200;
        tamanhopulseira = 18;
        System.out.println("Total: R$200,00\n");
    } else if(pulseira.toLowerCase().equals("grande")){
        pulseira = "grande";
        valorpulseira = 240;
        tamanhopulseira = 20;
        System.out.println("Total: R$240,00\n");
    }
    
    System.out.println("Agora escolha o pingente:");
    
  2. Create a condition - initially true - saying whether or not to continue on loop. So move your code into the loop (keep variable statements out, so that they remain accessible to the rest of the code, if applicable):

    String pingente; // Não leia ainda!
    int valorpingente = 0;
    double tamanhopingente = 0;
    int valor = 0;
    double tamanhofinal = 0;
    
    boolean continuar1 = true;
    while ( continuar1 ) { // Executa pelo menos uma vez, e repete
                           // enquanto continuar1 não ficar falso
    
        System.out.println("Agora escolha o pingente:");
        System.out.println("Bichinhos (1,3cm) - R$225,00\nBonequinhos (1,5cm) - R$185,00\nBerloques (0,5cm) - R$200,00\nCubinhos (1cm) - R$190,00\nRolinho (2cm) - Prata, Pedra e Esmaltados.");
        pingente = in.nextLine(); // Agora sim, leia
    
        if(pingente.toLowerCase().equals("bichinhos")){
            pingente = "bichinhos";
            valorpingente = 225;
            tamanhopingente = 1.3;
            System.out.println("Quantos?");
            int qntsbichinhos = in.nextInt();
            double tamanhobichinhos = qntsbichinhos*tamanhopingente;
            if(tamanhobichinhos > tamanhopulseira){
                System.out.println("Você escolheu um número de bichinhos que excede o tamanho da pulseira!");
            } else {
                int valorbichinhos = qntsbichinhos*valorpingente;
                valor = valorpulseira+valorbichinhos;
                tamanhofinal = qntsbichinhos*tamanhopingente+tamanhopulseira;
                System.out.println("\nTotal:" +valor);
            }
        }
    
        // ... (inserir as outras opções, também adaptadas)
    }
    

    (Note: do not test this code yet - for he will enter a loop infinite; see next item first)

  3. Finally, establish the necessary condition to exit the loop. In case, is if the user has chosen a valid size:

            } else {
                int valorbichinhos = qntsbichinhos*valorpingente;
                valor = valorpulseira+valorbichinhos;
                tamanhofinal = qntsbichinhos*tamanhopingente+tamanhopulseira;
                System.out.println("\nTotal:" +valor);
    
                continuar1 = false; // Isso fará com que o código não se repita mais
            }
    
  • Face perfect answer! But could you give me one more example? Because don’t mess with that while so that he can check the full size of the pendant and see if that size is bigger than the bracelet. Because in my code, Else makes sure that the user can only fill the entire bracelet with a kind of pendant, as it says here: if(tamanhobichinhos > tamanhopulseira){&#xA; System.out.println("Você escolheu um número de bichinhos que excede o tamanho da pulseira!");&#xA; } how do I make while perform this function to be able to use more pendants if it only chooses a few

  • 1

    In this case, it would be better to ask the user himself whether he wants to stop choosing or not. Because if he chose some pets and the size is smaller than the bracelet, how will the code know if he now wants to choose dolls or if he is already satisfied? What you can do is put one more choice option (sair) which - if chosen - makes continuar1 become false. Then, at each choice, you add the size x amount of each pendant, and compare the total with the size of the bracelet. If exceed, either you reset all or you just reset the last.

  • 1

    As the logic is more complex, it is much more difficult to do without breaking into functions. Unless your exercise requires it, my suggestion is to adopt a simpler method. I could try to help you more, but unfortunately I can’t devote much time to it today no (tomorrow or the day after I can, however).

  • Okay. I’ll try it anyway. If I can’t get you back here ;) Thanks for everything!

  • I came back to comment that everything worked fine! I redid the code using while. I will post as a reply to anyone who wants to evaluate and give me tips xD Thank you very much to everyone who responded and helped too!

2

Final code with while:

import java.util.Scanner;
public class Sistema_Bichara{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        //Primeiro Menu
        System.out.println("Digite o o número referente ao tamanho da pulseira\n1.Pequena (17cm) - R$180,00\n2.Média (18cm) - R$200,00\n3.Grande (20cm) - R$240,00");
        // Incio declaração de variáveis
        int digita = in.nextInt();
        double pagar = 0;
        double valor = 0;
        double valor2 = 0;
        int tamanhopulseira = 0;
        double tamanhototal = 0.0;
        // Fim declaraçaõ de variáveis
        // Inicio de opções de pulseiras e definido seus preços e tamanhos nas variáveis
        switch(digita){
            case 1:
            valor += 180;
            tamanhopulseira = 17;
            System.out.println("Total: R$180,00\nAgora escolha o(s) pingente(s):");
            break;
            case 2:
            valor += 200;
            tamanhopulseira = 18;
            System.out.println("Total: R$200,00\nAgora escolha o(s) pingente(s):");
            break;
            case 3:
            valor += 240;
            tamanhopulseira = 20;
            System.out.println("Total: R$240,00\nAgora escolha o(s) pingente(s):");
            break;
        }
        // Final da escolha da pulseira
        // Inicio da escolha dos 'enfeites' da pulseira com while para não ultrpassar o tamanho máximo da pulseira. Possui opção para ir direto para o pagamento no meio da escolha (caso não queria preencher o tamanho da pulseira inteiro)
        while (digita != 6 && tamanhototal < tamanhopulseira) {
        System.out.println("1.Bichinhos (1,3cm) - R$225,00\n2.Bonequinhos (1,5cm) - R$185,00\n3.Berloques (0,5cm) - R$200,00\n4.Cubinhos (1cm) - R$190,00\n5.Rolinho (2cm) - Prata, Pedra e Esmaltados\n6.Ir para o pagamento");
        digita = in.nextInt();
        switch(digita){
            case 1:
            valor += 225;
            tamanhototal += 1.3;
            break;
            case 2:
            valor += 185;
            tamanhototal += 1.5;
            break;
            case 3:
            valor += 200;
            tamanhototal += 0.5;
            break;
            case 4:
            valor += 190;
            tamanhototal += 1;
            break;
            case 5:
            tamanhototal += 2;
            System.out.println("Escolha o material:\n1.Prata - R$150,00\n2.Pedras - R$220,00\n3.Esmaltados - R$198,00");
            int rolinho = in.nextInt();
            switch(rolinho){
                case 1:
                valor += 150;
                break;
                case 2:
                valor += 220;
                break;
                case 3:
                valor += 198;
                break;
            }
        }
        if(tamanhototal > tamanhopulseira){
            System.out.println("\nTamanho máximo da pulseira atingido\n1.Prosseguir para o pagamento.");
            digita = in.nextInt();
    }

}
//Final escolha dos enfeites
//Começa processo de pagamento
    if(digita==6){
    System.out.println("\nDigite 1 para prosseguir para o pagamento.");
    digita = in.nextInt();
}
//Oferece o suporte de segurança e se dito que sim, acrescenta o valor de 95 reais no preço total do produto
    System.out.println("\nDeseja adquirir um suporte de segurança pelo preço de R$95,00?\n1.Sim\n2.Não");
    digita = in.nextInt();
    if(digita == 1){
        valor += 95;
}
//Continua o processo de pagamento informando o valor total da compra e oferecendo os tipos de pagamento
    System.out.println("\nO preço total da compra fica de: R$"+valor);
    System.out.println("\nA loja oferece os seguintes tipos de pagamento:");
    System.out.println("\n1. À vista com 5% de desconto");
    System.out.println("\n2. 3 vezes no cartão sem acrescimos");
    System.out.println("\n3. 5 vezes no cartão com acresimo de 10% no preço total");
    System.out.println("\n4. 10 vezes no cartão com acresimo de 20% no preço total");
    System.out.println("\nDigite o número da forma de pagamento escolhida.");
    digita = in.nextInt();
    //Pega o pagamento escolhido e aplica o cálculo matemático para descontos ou acrescimos de preço. Também calcula o valor de cada parcela caso seja parcelado.
    switch(digita){
        case 1:
        valor = valor*0.95;
        break;
        case 2:
        pagar = valor/3;
        break;
        case 3:
        valor2 = (valor*110)/100;
        pagar = valor2/5;
        break;
        case 4:
        valor2 = (valor*120)/100;
        pagar = valor2/10;
        break;
            }
    //Condição para mostrar o valor total de acordo com o pagamento escolhido
    if (digita == 3){
        System.out.println("\nO valor total da compra ficou de: R$" +valor2);
    } else if (digita == 4){
        System.out.println("\nO valor total da compra ficou de: R$" +valor2);
    } else {
        System.out.println("\nO valor total da compra ficou de: R$" +valor);
    }
    //Condição para mostrar o valor total e o valor das parcelas se a pessoa escolheu parcelado
    if(digita == 2){
    System.out.println("\nForma de pagameto: 3 parcelas de R$" +pagar);
    System.out.println("\nA loja aceita os seguintes cartões:\n1.Visa\n2.MasterCard\n3.Rede Shop\n4.American Express\n5.Hipercard\n6.Diners Club International");
    digita = in.nextInt();
}  else if(digita == 3){
    System.out.println("\nForma de pagameto: 5 parcelas de R$" +pagar);
    System.out.println("\nA loja aceita os seguintes cartões:\n1.Visa\n2.MasterCard\n3.Rede Shop\n4.American Express\n5.Hipercard\n6.Diners Club International");
    digita = in.nextInt();
}else if(digita == 4){
    System.out.println("\nForma de pagameto: 10 parcelas de R$" +pagar);
    System.out.println("\nA loja aceita os seguintes cartões:\n1.Visa\n2.MasterCard\n3.Rede Shop\n4.American Express\n5.Hipercard\n6.Diners Club International");
    digita = in.nextInt();
}
//Fim do sistema e agradecimento ao cliente
    System.out.println("\nObrigado por comprar conosco!");
}
}
  • Since you asked for tips, here are some to make your code more robust: 1) Nos switches, always use default in case the user chooses an invalid option; same thing when you do not test what you received (e.g.: in "Type 1 to proceed to payment"); in practice this is important, for this exercise do not need. 2) Your code the way it is alert when the full size has been exceeded, but it goes on anyway - the ideal would be to test it before upgrading valor and tamanhoTotal, for example alerting the user, not messing with the values and continuing with the loop.

  • (I say that in this exercise item 1 does not matter because it does not cover handling exceptions in any way, so if the user type a when you expect a number will go wrong anyway... best not to worry about it for now) Plus, good implementation, +1

Browser other questions tagged

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