I am stuck on this big time, I have been floundering here for like 4 hours and if anyone can help I would be SO grateful, I have this program that I have to write that I cannot grasp. I know ya'll dont like to have us noobs posting our "homework" in here but I am taking this online and my instructor sucks. Any helpful tips or expert guidance is all i'm asking for.

I have to develop a program for a "small company" that sells 5 products with the prices procuct 1 $2.98, product 2 $4.50, product 3 $9.98, product 4 $4.49, and product 5 $6.87. The application has to read in the product number and the quantity sold. The program has to use a switch statement to determine the retail price for each product. It should calculate and display the total retail value of all products sold. It also has to use a sentinel-controlled loop to determine when the program should stop looping and display the final results.

Unfortunately I took this class as an elective and this is my final project. I have looked over this over and over and my book sucks!! Any help from you experts out there would be greatly appreciated. Thanks!

Dani AI

Generated

Solid start, — the flow in Post #3 is good and 's points about closing the stream and formatting output are helpful. Two things to tighten so the program matches the usual interpretation of a "sentinel-controlled loop" assignment and is robust in real use:

  • Use a numeric sentinel (for example, enter product 0 to finish) instead of a 'y'/'n' prompt. That keeps the product/quantity input paired and is easier for automated grading.
  • Avoid double for money calculations. Use BigDecimal or integer cents to prevent rounding surprises and to make formatting exact.

A compact example showing a numeric sentinel and BigDecimal price mapping:

import java.util.Scanner;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class SalesSentinel {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            BigDecimal[] price = {
                BigDecimal.ZERO,
                new BigDecimal("2.98"),
                new BigDecimal("4.50"),
                new BigDecimal("9.98"),
                new BigDecimal("4.49"),
                new BigDecimal("6.87")
            };
            BigDecimal total = BigDecimal.ZERO;
            while (true) {
                System.out.print("Product (1-5, 0 to finish): ");
                int p = sc.nextInt();
                if (p == 0) break;
                if (p < 1 || p > 5) { System.out.println("Invalid product"); continue; }
                System.out.print("Quantity: ");
                int q = sc.nextInt();
                if (q <= 0) { System.out.println("Quantity must be positive"); continue; }
                total = total.add(price[p].multiply(new BigDecimal(q)));
            }
            System.out.println("Total = $" + total.setScale(2, RoundingMode.HALF_UP));
        }
    }
}

Troubleshooting notes: guard input (use hasNextInt() or catch InputMismatchException), test invalid product numbers and negative quantities, and prefer setScale(2, RoundingMode.HALF_UP) or a DecimalFormat pattern like #,##0.00 for display. Splitting line-total calculation into a small method makes unit testing and debugging easier.

Recommended Answers

All 4 Replies

Don't worry about being a "noob". We all have to start somewhere. Start out with a BufferedReader to read from the command line:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Once you have that, then you can read the product number and that good stuff.

Then just use a switch statement to test the input.

Show me what you have so far, and I can help further.

This is it so far without testing, what do you think? Sorry if its hard to read, havnt done any commenting or anything yet.


import java.io.*;

public class Sales
{
public static void main(String[] args)
{
double total = 0.0;
BufferedReader br = null;
try
{
br = new BufferedReader(
new InputStreamReader(System.in));
boolean readMore = true;
while(readMore)
{
System.out.println("enter product number");
String prodNum = br.readLine();
System.out.println("enter quantity");
String numDesired = br.readLine();
int number, quantity;
try
{
number = Integer.parseInt(prodNum);
quantity = Integer.parseInt(numDesired);
}
catch(NumberFormatException nfe)
{
System.err.println("cannot parse: " + nfe.getMessage());
continue;
}
switch(number)
{
case 1:
total += 2.98 * quantity;
break;
case 2:
total += 4.50 * quantity;
break;
case 3:
total += 9.98 * quantity;
break;
case 4:
total += 4.49 * quantity;
break;
case 5:
total += 6.87 * quantity;
}
System.out.println("order more? 'y' or 'n'");
String decision = br.readLine();
if(!decision.equals("y"))
readMore = false;
}
br.close();
}
catch(IOException ioe)
{
System.err.println("read: " + ioe.getMessage());
}
System.out.println("total cost = " + total);
}
}

Looks really good. I wouldn't change much at all. The only thing I would do is put the close() method in a finally clause, and add a decimalformat instance to the mix. Something like this:

import java.io.*;
import java.text.*;

public class Sales
{
	public static void main(String[] args)
	{
		double total = 0.0;
		BufferedReader br = null;
		DecimalFormat dec = new DecimalFormat("###,###.##");
		try
		{
			br = new BufferedReader(new InputStreamReader(System.in));
			boolean readMore = true;
			while(readMore)
			{
				System.out.print("Enter the product # -->  ");
				String prodNum = br.readLine();
				System.out.print("Enter the quanity -->  ");
				String numDesired = br.readLine();
				int number, quantity;
				try
				{
					number = Integer.parseInt(prodNum);
					quantity = Integer.parseInt(numDesired);
				}
				catch(NumberFormatException nfe)
				{
					System.err.println("cannot parse: " + nfe.getMessage());
					continue;
				}
				switch(number)
				{
					case 1:
					total += 2.98 * quantity;
					break;
					case 2:
					total += 4.50 * quantity;
					break;
					case 3:
					total += 9.98 * quantity;
					break;
					case 4:
					total += 4.49 * quantity;
					break;
					case 5:
					total += 6.87 * quantity;
				}
				System.out.print("Would you like to order more?  'y'/'n' -->  ");
				String decision = br.readLine();
				if(!decision.equals("y"))
				{
					readMore = false;
				}
			}
	     }
	     catch(IOException ioe)
	     {
		System.err.println("read: " + ioe.getMessage());
             }
             finally
	     {
		     try
		     {
			     br.close();
		     }
		     catch(IOException ioe)
		     {
			     System.out.println("Could not close stream");
		     }
	     }
		System.out.println("total cost = $" + dec.format(total));
	}
}

Other than that, You've done an excellent job.

Thanks for the pointer!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.