Shopping Cart Java

Asked

Viewed 382 times

0

I have doubts about the creation of a shopping cart, I managed so far: Inform the product name, Product price Quantity; there is the sum and the question if you make another purchase, if it is "N" it ends, otherwise it restarts.

Then it has to be informed a cycle and then add up all the values dividing in cash or card.

package problema01;

import java.io.IOException;
import java.util.Scanner;

/**
 *
 * @author VAGNER.MATOS
 */
public class Problema01 {

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */

      public static void main(String[] args) throws IOException{
        Scanner ent = new Scanner(System.in);
        Scanner ler = new Scanner(System.in);

        double num, preço;
        String nome;
        String nome2;
        char resposta;

            System.out.println("Informe o Produto:");// Usuario digita o nome do produto
            nome = ler.nextLine();
            System.out.println("Digite o preço do Produto");// usuario digita o preço
            preço = ent.nextDouble(); 
            System.out.println("Digite a quantidade do Produto"); // usuario digita a quantidade do produto
            num = ent.nextDouble();

            System.out.println("A Quantidade de produtos é "+num+"\nTotal a pagar é R$"+num*preço+"\n\nObrigado por comprar "+nome); // Resumo

            //Nova Compra        
            System.out.println("\nRealzar outra compra? (S/N): "); //entrada de dados (lendo um caractere)
            resposta = (char)System.in.read();
                if ((resposta == 'S') || (resposta == 's'));
{
                System.out.println("\n\"Nova compra\"\n");
                System.out.println("Favor iniciar com as informações\n");
                System.out.println("Informe o Produto:");
                nome2 = ler.nextLine();//Novo produto
                System.out.println("Digite o preço do Produto");
                preço = ent.nextDouble(); // usuario digita o preço              
                System.out.println("Digite a quantidade do Produto");
                num = ent.nextDouble(); // usuario digita a quantidade do produto
                System.out.println("A Quantidade de produtos é " + num + "\nTotal a pagar é R$"+ num*preço +"\n\nObrigado por comprar " + nome2);
}               System.out.println("\n\n\"Volte sempre!\"\n\n");

    }
}

2 answers

1


It makes no sense to create two Scanner's read from the same place (in this case from System.in). Use one.

Another detail is this semicolon after the if:

if ((resposta == 'S') || (resposta == 's'));
                                           ^ esse aqui

When you do that, you’re saying that inside the if has an empty block. That is, if the answer is S or s, you don’t do anything. And all that comes after is not part of the if and is always executed. Remove this ; hence.

I don’t understand why the amount should be a double. Is it possible for someone to buy something like "2.6 products"? If it doesn’t exist, change the variable type to int.

And if you’re wearing one Scanner, there is no reason to mix the readings with System.in.read.

Another detail is that if you want to repeat the same thing over and over again, you have to use one loop (in this case I would use a while, for example). Anyway, an alternative would be:

Scanner ent = new Scanner(System.in);
while (true) {
    System.out.println("Informe o Produto:");// Usuario digita o nome do produto
    String nome = ent.nextLine();
    System.out.println("Digite o preço do Produto");// usuario digita o preço
    double preço = ent.nextDouble();
    System.out.println("Digite a quantidade do Produto"); // usuario digita a quantidade do produto
    int num = ent.nextInt();
    ent.nextLine(); // consumir o ENTER, para não atrapalhar a próxima leitura: /q/262976/112052

    System.out.println("A Quantidade de produtos é " + num + "\nTotal a pagar é R$" + num * preço + "\n\nObrigado por comprar " + nome); // Resumo

    // Nova Compra
    System.out.println("\nRealzar outra compra? (S/N): "); // entrada de dados (lendo um caractere)
    String resposta = ent.nextLine();
    if ("n".equalsIgnoreCase(resposta))
        break; // sai do while(true)

    System.out.println("\n\"Nova compra\"\n");
    System.out.println("Favor iniciar com as informações\n");
}
System.out.println("\n\n\"Volte sempre!\"\n\n");

Of course you can improve more. If a number is not entered, nextDouble and nextInt give error. Also, these methods do not consume line break, and the next time you call nextLine, the result will be unexpected (so there is the extra call from nextLine to consume line break, as explained in detail here).

Instead of System.in.read I used the Scanner, and made the comparison case insensitive to decide whether or not to leave the while. But I only check if it was typed "n", so if it is typed anything else, it proceeds.

Anyway, a slightly better alternative is to create specific methods to validate each of these cases:

double lerPreco(Scanner sc, String mensagem) {
    while (true) {
        System.out.println(mensagem);
        try {
            return Double.parseDouble(sc.nextLine());
        } catch (NumberFormatException e) {
            System.out.println("Número inválido");
        }
    }
}

int lerQuantidade(Scanner sc, String mensagem) {
    while (true) {
        System.out.println(mensagem);
        try {
            return Integer.parseInt(sc.nextLine());
        } catch (NumberFormatException e) {
            System.out.println("Número inválido");
        }
    }
}

String lerOpcao(Scanner sc, String mensagem) {
    while (true) {
        System.out.println(mensagem);
        String opcao = sc.nextLine().toLowerCase();
        if ("s".equals(opcao) || "n".equals(opcao))
            return opcao;
        else
            System.out.println("A opção deve ser S ou N");
    }
}

Then just use these methods on loop main. And as you said you want to calculate the total of all purchases, just create a new variable for this and go adding inside the loop:

Scanner ent = new Scanner(System.in);
double total = 0;
while (true) {
    System.out.println("Informe o Produto:");// Usuario digita o nome do produto
    String nome = ent.nextLine();
    double preço = lerPreco(ent, "Digite o preço do Produto");
    int num = lerQuantidade(ent, "Digite a quantidade do Produto");
    double valor = num * preço;

    System.out.printf("A Quantidade de produtos é %d\nTotal a pagar é R$%.2f\n\nObrigado por comprar %s\n", num, valor, nome);
    total += valor;

    // Nova Compra
    String resposta = lerOpcao(ent, "\nRealzar outra compra? (S/N): ");
    if ("n".equalsIgnoreCase(resposta))
        break; // sai do while(true)

    System.out.println("\n\"Nova compra\"\n");
    System.out.println("Favor iniciar com as informações\n");
}
System.out.printf("Total das compras: R$%.2f\n", total);
System.out.println("\n\n\"Volte sempre!\"\n\n");

I also used printf to always format the value to two decimal places. However, if you are working with monetary values, better not to use double.

0

So, your question is a little complicated to understand, but from what I read, you want to work with a dynamic amount of information, IE, the user will keep entering the data, until he decides to stop, that would be the input 'N'.

For these types of situations one way to solve is by using a repetition structure like the while, that is to say:

Scanner sc = new Scanner(System.in);
String nome;
double preco;
double num;

char resposta = 'S';

while (resposta=='S'){
  #Entradas do usuário aqui
}

Note that there was only the need for a single Scanner to work with the inputs, in addition, I have already initialized the variable reply to enter the loop that will continue until response == 'N'.

I hope I’ve helped!

  • Thank you very much, as I said I’m new in programming, but your help was critical to my project! I managed to set up a while structure, but I still have to make the sum on the card and money, I’ll see how your codes got here. Thanks!

  • I thank you, any other doubt can play here, thanks!!

  • Good afternoon! I still haven’t been able to test the code, as I reported, I’m starting programming, so I need the complete code to be able to test

Browser other questions tagged

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