4 Replies - 528 Views - Last Post: 03 May 2012 - 02:50 PM Rate Topic: -----

#1 woodlandsrider  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 20-April 12

Need help with adding a loop

Posted 02 May 2012 - 09:33 PM

So I'm finishing up this code that I have been writing about a storefront program where it allows the user to enter in a customers info, check product prices, write up a total bill, and exit. I've written the entire program except for the part of writing up the total bill. I have run into a snag where the program was to just ask the user for a single product to be added to the bill to now it needs to be able to accept multiple products and quantities of each for the bill. In doing this I need a loop. I am having trouble as to which one I can do because whenever I put a "for" loop, it just repeats the one "system.out.print" statement the number of times the user entered for the quantities of different products question asked at the beginning, rather than having the program let the user enter the answer to how many of that product they would like per however many items they needed to enter. Here's the section I am working on

// Add ARRAY:
			// Modify your program to do the following:
			// The sales associate should now be allowed to enter multiple products to be displayed on the total bill. Modify your 
			// program to include a loop that will ask the sales associate the products the customer is purchasing and the quantity.
			// This loop should continue until the sales associate decides to not enter any more products.  Store this information in an array.
			// Display the total bill to your sales associate with all of the products entered.  (You can use an array or an arrayList)  
			// Hint*You will need to loop through the array or arrayList to display the products, quantity and price in the totalBill.
						
						
						//Variables
						int numProd;
						
						System.out.print("Quantity of different products: ");
						numProd = keyboard.nextInt();
						
						for(int count = 1; count <= numProd; count++)
						
      				{
						System.out.print( "\n" + "Enter 1,2,3,4, or 5 to select the coresponding product for choice item number "+count+":" ); 
        				System.out.println();
						}
						System.out.println( "\n" + 
		  										"1 = Shoes \n" +
												"2 = T-Shirts \n" +
												"3 = Shorts \n" +
												"4 = Caps \n" +
												"5 = Jackets \n"); 
						
  	
        				System.out.print("Select Product: "); 
						
						
						
						product1 = keyboard.nextInt(); 							// Allows user to enter name of product.

  						
						
						//Create an ArrayList for the products entered
						ArrayList<String> productList = new ArrayList<String>();
	
								while(product1 <1 || product1 >5) 
								{ 
		
									System.out.println("\n" + "You have entered an invalid option.  \n" +
															 "You must select a value of 1 through 5. \n" +
															 "\n" + "Please re-enter your selection. \n");
	
					 				// If not 1 - 4 returns user to main menu.
									product1 =  keyboard.nextInt(); 
								}
        
								
								
    			   			if (product1 == 1)
   		      			{  
  									System.out.println("\n" + "Shoes:  $10.01 \n" );
									product = "Shoes";
									price = 10.01;

	           				}

           					else if (product1 == 2)
            				{

                				System.out.println("\n" + "T-Shirts:  $20.02 \n");
									product = "T-Shirts";
									price = 20.02;
								}
					
								else if (product1 == 3)
            				{
              					System.out.println("\n" + "Shorts:  $30.03 \n");
									product = "Shorts";
									price = 30.03;
								}
					
								else if (product1 == 4)
            				{
            					System.out.println("\n" + "Caps:  $40.04 \n");
									product = "Caps";
									price = 30.03;
								}
				
								else if (product1 == 5)
            				{
           						System.out.println("\n" + "Jackets:  $50.05 \n");
									product = "Jackets";
									price = 40.04;
								}
								
							//Hold ArrayList
							productList.add(""+product+"");
							
						
					   	

						System.out.print( "Enter Quantity: " ); 
						int quantity = keyboard.nextInt(); 
						System.out.println();
												
						
						
					



Is This A Good Question/Topic? 0
  • +

Replies To: Need help with adding a loop

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8016
  • View blog
  • Posts: 31,118
  • Joined: 06-March 08

Re: Need help with adding a loop

Posted 03 May 2012 - 08:40 AM

Would be a lot easier if you have a class Product that holds the product name, its quantity and the unit price
The ArrayList van be an ArrayList of Product and should be created before the loop
You can have a product number like 999 to exit the loop
A switch() statement is a lot better than multiple if

class Product {
   String name;
   int quantity;
   double price;

   // constructor
   Product(String name, int quantity, double price) {
      this.name = name;
      this.quantity = quantity;
      this.price = price;
   }
}


Now in your main() method

    ArrayList<Product>al = new ArrayList<Product>();

    while(true) {
       System.out.println("  1) for shoes");
       System.out.println("  2) for jackets");
       ...
       System.out.println("999) to exit");
       int num = scanner.nextInt();
       if(num == 999)
          break;         // done exit the loop

       int quantity = scanner.nextInt();
       switch(num) {
          case 1:
             Product p = new Product("Shoes", quantity, 15.0);
             al.add(p);
             break;
          case 2:
             Product p = new Product("Jackets", quantity, 35.0);
             al.add(p);
             break;
          ...
          default:
             System.out.println("This is an invalid product number");
             break;
        } // end switch
     } // end while
 
     // prepare bill
     double total = 0;
     for(int i = 0; i < al.size(); ++i) {
         Product p = al.get(i);
         total = total + (p.price * p.quantity);
         System.out.println(p.name + " nb: " + p.quantity + " $" + p.price);
     }
     System.out.println("Total: " + total);



Happy coding
Was This Post Helpful? 0
  • +
  • -

#3 tstennette  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 12-February 12

Re: Need help with adding a loop

Posted 03 May 2012 - 09:20 AM

Just a very small improvement @pbl's solution, instead of entering 999 to exit the program, you could have it to where the user enters either 0 or -1. Just as good practice, you want the exit # to be impossible for the user to enter and have something done other than exiting the program. I know it probably won't matter in this program, but what if later on down the road you get 999+ items? Unless for some reason you want an item # 0 or -1 :P
Was This Post Helpful? 0
  • +
  • -

#4 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon

Reputation: 5421
  • View blog
  • Posts: 8,705
  • Joined: 19-March 11

Re: Need help with adding a loop

Posted 03 May 2012 - 09:26 AM

I thought it was pretty obvious that this was not a program intended for eventual deployment. In a long-term scenario, you'd probably have a UI that was a little less crufty than this in many ways. :)
Was This Post Helpful? 0
  • +
  • -

#5 woodlandsrider  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 20-April 12

Re: Need help with adding a loop

Posted 03 May 2012 - 02:50 PM

Alright, so I think it would be better for me to post my entire program so that you can get a feel for what I need to be doing, here it is

/**------------------------------------------------------------------------------------------------------

Author: Sam Mann and Scott Mercurio

We worked as a team to complete this project


		
				
*/


import java.util.ArrayList;  // Needed for the ArrayList class
import java.util.Scanner;  // Needed for the Scanner class.
import java.io.*; 


public class SamP3 
{



	public static void m1CustomerInfo() throws java.io.IOException
	{


						
						
						Scanner keyboard = new Scanner(System.in);

         			// Get customer name.
         			System.out.print( "\n" + "Enter Customer Name:  ");
         			String name = keyboard.nextLine();
						
						PrintWriter outputFile = new PrintWriter(""+name+"");

         			// Store Customer Name
         			outputFile.println(name);
      
		
		
         			// Get customer Street Address.
         			System.out.print("Enter Customer Street Address:  ");
         			String address1 = keyboard.nextLine();

         			// Store customer Street Address.
         			outputFile.println(address1);
			
			
			
						// Get customer State, City and Zip Address.
         			System.out.print("Enter Customer State, City and Zip Code:  ");
         			String address2 = keyboard.nextLine();

         			// Store customer Street Address.
         			outputFile.println(address2);
			
			
			
         			// Get customer email.
         			System.out.print("Enter Customer Email:  ");
         			String email = keyboard.nextLine();

         			// Write customer email to the file.
         			outputFile.println(email);


      				System.out.println();

      				// Close the file.
      				outputFile.close();
     					System.out.println("Name:        " + name);
      				System.out.println("Street:      " +address1);
						System.out.println("City St Zip: " +address2);
      				System.out.println("Email:       " + email);
      				System.out.println("-----------------------------");
						System.out.println("Data above written to file. \n" + 
												 "- Location: [C:]    \n" + 			
												 "- Name:     [C:\\" + name + ".txt] ");
							

		}//Close m1 CustomerInfo method




// Start m2
				public static void m2PriceLookUp()  throws java.io.IOException
				{
			
				Scanner keyboard = new Scanner( System.in ); 
			
									// Variables
									int priceCheck;
			
			
			        				System.out.print( "\n" + "Enter 1,2,3,4, or 5 to check \n" + 
					  										"the price for the coresponding product:    " );  
			        				System.out.println();
			        				System.out.println( "\n" + 
					  										"1 = Shoes \n" +
															"2 = T-Shirts \n" +
															"3 = Shorts \n" +
															"4 = Caps \n" +
															"5 = Jackets \n"); 
			  	
			        				System.out.println("Enter Option: "); 
			
			
			        				priceCheck = keyboard.nextInt(); 
			  
			
				
											if(priceCheck <1 || priceCheck >5) 
											{ 
					
												System.out.println("\n" + "You have entered an invalid option.  \n" +
																		 "You must select a value of 1 through 5. \n" +
																		 "\n" + "Please re-enter your selection. \n");
				
								 				// If not 1 - 4 returns user to main menu.
												priceCheck =  keyboard.nextInt(); 
											}
			        
			
			    			   			if (priceCheck == 1)
			   		      			{  
								     
			  									System.out.print("\n" + "Shoes:  $10.00 \n" );
											
			
				           				}
			
			           					else if (priceCheck == 2)
			            				{
			                			System.out.print("\n" + "T-Shirts:  $20.00 \n");
											}
								
											else if (priceCheck == 3)
			            				{
			              				System.out.print("\n" + "Shorts:  $30.00 \n");
											}
								
											else if (priceCheck == 4)
			            				{
			            				System.out.print("\n" + "Caps:  $40.00 \n");
											}
							
											else if (priceCheck == 5)
			            				{
			           					System.out.print("\n" + "Jackets:  $50.00 \n");
											}
			
			
			
				}// Close m2PriceLookUp method


// Start m3
				public static void m3CaluclateBill() throws java.io.IOException
				{

						Scanner keyboard = new Scanner( System.in ); 

						// Constant:  Needed to preform math calculations.
						double taxRate = 0.08;	// The tax rate
						double price = 0.00;    // Sets initial price

						// Variables:  Needed for system out.
						String name;			// Needed to store variable Customer Name
						String product = "empty";  //	Needed to store variable Product
						//Variables
						int product1 = 0;		//	Needed to store variable Price
						
						System.out.print( "\n" + "Enter customer name: " ); 	// Displays text: "Enter customer name:"
						name = keyboard.nextLine();									
						
												
						// Make sure file exists.
						File file = new File (""+name+"");
						while (!file.exists())
						{
						
							//If file does not exist it run provides this response.
							System.out.print("\nThe customer name '"+name+"' is not found.");
							System.out.println();
							System.out.print("\nCheck the spelling and re-enter the customer name again.\n" +
											     "\nRe-Enter customer name: ");
	
							//After error msg, allows user to make another attempt.
							name = keyboard.nextLine();
							file = new File (""+name+"");	

						}

						Scanner inputFile = new Scanner(file);
	
//--------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------------------		

		   // Add ARRAY:
			// Modify your program to do the following:
			// The sales associate should now be allowed to enter multiple products to be displayed on the total bill. Modify your 
			// program to include a loop that will ask the sales associate the products the customer is purchasing and the quantity.
			// This loop should continue until the sales associate decides to not enter any more products.  Store this information in an array.
			// Display the total bill to your sales associate with all of the products entered.  (You can use an array or an arrayList)  
			// Hint*You will need to loop through the array or arrayList to display the products, quantity and price in the totalBill.
						
						
		  				//Variables
						int numProd;
						
						System.out.print("Quantity of different products: ");
						numProd = keyboard.nextInt();
						
						for(int count = 1; count <= numProd; count++)
						
      				{
						System.out.print( "\n" + "Enter 1,2,3,4, or 5 to select the coresponding product for choice item number "+count+":" ); 
        				System.out.println();
						}
						System.out.println( "\n" + 
		  										"1 = Shoes \n" +
												"2 = T-Shirts \n" +
												"3 = Shorts \n" +
												"4 = Caps \n" +
												"5 = Jackets \n"); 
						
  	
        				System.out.print("Select Product: "); 
						
						
						
						product1 = keyboard.nextInt(); 							// Allows user to enter name of product.

  						
						
						//Create an ArrayList for the products entered
						ArrayList<String> productList = new ArrayList<String>();
	
								while(product1 <1 || product1 >5) 
								{ 
		
									System.out.println("\n" + "You have entered an invalid option.  \n" +
															 "You must select a value of 1 through 5. \n" +
															 "\n" + "Please re-enter your selection. \n");
	
					 				// If not 1 - 4 returns user to main menu.
									product1 =  keyboard.nextInt(); 
								}
        
								
								
    			   			if (product1 == 1)
   		      			{  
  									System.out.println("\n" + "Shoes:  $10.01 \n" );
									product = "Shoes";
									price = 10.01;

	           				}

           					else if (product1 == 2)
            				{

                				System.out.println("\n" + "T-Shirts:  $20.02 \n");
									product = "T-Shirts";
									price = 20.02;
								}
					
								else if (product1 == 3)
            				{
              					System.out.println("\n" + "Shorts:  $30.03 \n");
									product = "Shorts";
									price = 30.03;
								}
					
								else if (product1 == 4)
            				{
            					System.out.println("\n" + "Caps:  $40.04 \n");
									product = "Caps";
									price = 30.03;
								}
				
								else if (product1 == 5)
            				{
           						System.out.println("\n" + "Jackets:  $50.05 \n");
									product = "Jackets";
									price = 40.04;
								}
								
							//Hold ArrayList
							productList.add(""+product+"");
							
						
					   	

						System.out.print( "Enter Quantity: " ); 
						int quantity = keyboard.nextInt(); 
						System.out.println();




						
						
																		
						
						
					
					
//--------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------------------



						System.out.print("-----------------------------------------------" ); 
						System.out.println();
						while (inputFile.hasNext())
						{
						   // 
							String customerInfo = inputFile.nextLine();
							
							// Prints all data in the file.
							System.out.println(customerInfo);

						}
						
						inputFile.close();					 
						
						System.out.println();

						


						double totalPrice = quantity * price;					// The total of Price, Quantity * Price.
						double totalTax = totalPrice * .08;				   	// The total of Tax, totalPrice * 1.08.			
						double totalCost = totalPrice + totalTax;				// The total of Cost, totalPrice + totalTax.
  
						System.out.println( "\n" +				// Print out the following:


											// Prints row: Product Pruchased     Quantity    Total Cost
											"Product Purchased" + "     " + 
											"Quantity" + "      " +  
											"Total Cost" + 
											"\n" +

											// Prints row: productEntered        quantityEntered       totalPrice

											productList +  "              	" +  			// Displays Product as entered  +
											quantity +  "              " + 					// Displays Quantity as entered  +


																								// String.format("%.2f, ??? variableName ???)
														" $" + String.format("%.2f", totalPrice) +  	// formats decimal place to two digits 
												// Displays "$" and the variable totalPrice
											" \n" +
									
											// Prints row: Tax and taxRate							          Displays variable:	totalTax							// String.Format
											"Tax (@" + taxRate + "%):" +  "                            $" + String.format("%.2f", totalTax)	+ " \n" +	//
																																															// "%.2f
											// Prints row: Total Cost								   Displays variable: totalCost										// holds two
											"Total Cost: " +  "                            $" + String.format("%.2f", totalCost) + " \n" +					// decimal places

											"-----------------------------------------------");	// Ends message (with "no period")
										


				}// Close m3CaluclateBill method
				




// Start m4
				public static void m4MainMenu() throws java.io.IOException
				{

					System.out.print( "\n" + "You have quit the program.  Good-bye." + "\n" ); 

					// Ends Program		
					System.exit(0);


				}// Close m4MainMenu method




    public static void main(String[] args) throws java.io.IOException
    {
       
        int number = 0;    // Set number to 0 to promt menu.

		  // Create a Scanner object for keyboard input
        Scanner userInputKeyboard = new Scanner( System.in );


	

        

				while(number != 4)
				{
				
				
				         
				System.out.println();
				System.out.println();
         	// Get the menu option from the user.
     	  		 System.out.print("Select one of the following options \n" +
			  						   "by entering 1, 2, 3, or 4 on your keyboard:\n" +
      								"\n" +     
		  								"1 = Enter Customer Information\n" +
        								"2 = Price Lookup\n" +
        								"3 = Display Total Bill\n" +
        								"4 = Quit \n");
      		System.out.println();

      		System.out.print("Enter Option: ");
          

        		 number = userInputKeyboard.nextInt();
			
					while (number  <1 || number >4) 
					{ 
					System.out.println("\n" + "You have entered an invalid option.  \n" +
											 "You must select a value of 1, 2, 3, or 4. \n" +
											 "Please re-enter your selection. \n");

						 // If not 1, 2, 3, 4 returns user to main menu.


						number =  userInputKeyboard.nextInt(); 
					}

				
				
				

// Option 1 
    			   if (number == 1)
   		      {// Starts IF
					     
    				
 					m1CustomerInfo();

    					 
				
	           	}// Closes IF

           		
// Option 2 					
					else if (number == 2)
					
    				{ 

 					m2PriceLookUp();
        			
 		   		} // close else if option 2


// Option 3 
					else if (number == 3)
					// Case 3 

    				{

					m3CaluclateBill();
			
    				} // close else if option 3
 			



	    			}// While (number != 4)
					//  Option 4
					m4MainMenu();
	
	               
	
	         	}  // Closes While

    }  // Closes Main





Mainly needing help from line 200 down to the end.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1