Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

java - I have to do this task (online shop) using "switch" statements. I got stuck

"Write a Java program to simulate an online store. The program should begin by displaying a list of products and their prices. There should be a minimum of 4 products offered.

My code is below, it works without the strings but I need to have names for the cakes(display names and prices)

import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
    Scanner input= new Scanner(System.in)

    
    int cakeNo = 0;
    double cake1;
    double cake2;
    double cake3;
    double cake4;
    double cake5;
    int quantity;
    
    double totalSales = 0;
    
    while(cakeNo !=0 )
     
     System.out.println("Enter cake number 1-5");
     cakeNo=input.nextInt();
     
     System.out.println("Enter quantity");
     quantity = input.nextInt();
     
     switch (cakeNo){
         
         case 1: cake1 = 3.70;
     totalSales+=(3.70*quantity);
     break;
         case 2: cake2 = 4.20;
     totalSales+=(4.20*quantity);
     break;
         case 3: cake3 = 4.50;
     totalSales+=(4.50*quantity);
     break;
         case 4: cake4 = 5.00;
     totalSales+=(5.00*quantity);
     break;
         case 5: cake5 = 5.50;
     totalSales+=(5.50*quantity);
     break;
     
     }
     
     System.out.println(totalSales);  
}  
    
}

Thank you so much for reading! Please help if you have an idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well there are a few things wrong in your code that you should take care first.

First: The first 5 string are wrongly defined. It should be like this String cake1 = "Angel cake" and so on.

Second: The strings and doubles have the same names you cannot do that. You need to have something like String cake1Name = "Name" and double cake1Price = price this way you have two distinct properties for everycake.

Third: Right now the code doesn't even enters the while loop. Since cakeNo starts with 0 and the condition in your while loop is cakeNo != 0 right on before the first loop this condition will be tested and it will be false meaning that the loop code won't be executed and will jump to the end of the program.

After this fixes there is still a little problem. After you get the input from the user if said input is 0 meaning that he wants to leave the program will still ask him for a quantity. You need to add/change something that breaks the loop when this conditions is true. I don't want to give you code but I hope this answer can help you good luck :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...