Solved

Storing loop input values Java

Posted on 2013-01-14
15
352 Views
Last Modified: 2013-01-16
Hello

I am trying to teach myself java, basically from books and youtube videos. I came across the question below in a book and I am having trouble finding out how to display the value of each main course entered. I haven't covered arrays yet but I assume the multiple values can be stored an displayed using an array???  

All my keyboard input for the main course choice is being stored in a variable called choice! How do I print the values of each maincourse choice inputted?

A restaurant offers 4 main course options on its menu,
1. Turkey and Ham
2. Steak (€5 supplement)
3. Nut roast (vegetarian)
4. Lasagne
A Java program is required that first displays the menu, and then ask the user to
enter the number of people in their party. For each person in the party the
program should read their choice of main course. The program should count and
display the number of each main course chosen, and the total cost of the booking.

import java.util.Scanner;

public class DinnerParty
{
	public static void main (String [] args)
	{
		//print out the menu
		System.out.println ("1. Turkey and Ham \n2. Steak (€5 supplement)\n3. Nut roast (vegetarian €3 discount)\n4. Lasagne");
		
		System.out.println();//new line
		
		int partyNum;
		int choice = 0;
		int order;
		int count = 0;
		int total = 0;
		double mainCourse;
		int i = 0;
			
		Scanner kb = new Scanner(System.in);
		//get the user to enter the number of people in their party (Scanner class)
		System.out.println ("Please enter the number of people in your party");
		partyNum = kb.nextInt();
		
		//display number in party
		System.out.println("The number in your party is " + partyNum);
		
		// Read each member of the partys main course
				
		System.out.println();//new line
		
		System.out.println ("Please enter the Maincourse " +
		"order for each of your party");
		
		for(i = 1; i <= partyNum; i++)
		{
			choice = kb.nextInt();
			
			System.out.println("Person " + i + " will have maincourse no: " +choice);
			count++;
		}
		
		//Count and display the number of each main course chosen
		 System.out.println("The total orders place are " + count);
		 
		 System.out.println("The orders placed were " + choice);
		 
		// display the total cost of the booking
		System.out.println("The total cost of all " + count + " orders is " + total);

	}
}

Open in new window

0
Comment
Question by:Kevin_Coors
  • 8
  • 7
15 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 38774451
Sounds to me like you could use a couple of classes - one for the menu containing all the choices and prices, and the other one representing a diner (a person, not a US-style roadside bistro).
0
 

Author Comment

by:Kevin_Coors
ID: 38774516
Thanks Krakaota. I haven't reached classes yet. But I realise I wil have to get used to them as java is Object Oriantated :)
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38774675
Your code above *is* a class already . . . that's what that identifier 'class' is doing there right at the top. ;)
0
 

Author Comment

by:Kevin_Coors
ID: 38774703
Thanks Krakatoa

My real problem here is trying to get the program to display each dinner party members order and the total cost of the full partys dinner order? I have restructered the code to make it easier to understand (hopefully)
Do I need a 2nd for loop  to display the individual choices and calculate the total cost for n meals

import java.util.Scanner;

public class DinnerParty
{
	public static void main (String [] args)
	{
		System.out.println ("1. Turkey and Ham \n2. Steak (€5 supplement)\n3. Nut roast (vegetarian €3 discount)\n4. Lasagne");
		System.out.println();//new line
		
		int partyNum;
		int choice = 0;
		int order = 0;
		int count = 0;
		int total = 0;
		double mainCourse;
		int i = 0;
	   double orderNumOne = 22.00;
		double orderNumTwo = 27.00;	
		double orderNumThree= 19.00;	
		double orderNumFour= 22.00;		
			
		Scanner kb = new Scanner(System.in);
		//get the user to enter the number of people in their party (Scanner class)
		System.out.println ("Please enter the number of people in your party");
		partyNum = kb.nextInt();
		
		//display number in party
		System.out.println("The number in your party is " + partyNum);
		
		// Read each member of the partys main course
		System.out.println();//new line
		
		System.out.println ("Please enter the Maincourse order for each of your party");
		
			for(i = 1; i <= partyNum; i++)
			{
				choice = kb.nextInt();
				System.out.println("Person " + i + " will have maincourse no: " +choice);
				 
				 count++;
				
				 if(choice == 1){
				 		System.out.println("Your maincourse cost is £ " + orderNumOne);
				 }else if (choice == 2){
				 		System.out.println("Your maincourse cost is £ " + orderNumTwo);
				 }else if (choice == 3){
				 		System.out.println("Your maincourse cost is £ " + orderNumThree);
				 }else 
				 System.out.println("Your maincourse cost is £ " + orderNumOne);
				 
				 total = count + choice;
			}
			 //Count and display the number of each main course chosen
	       System.out.println("The total orders placed was " + count);
			 // Display the total cost of the order
			 System.out.println("The total cost of the orders placed is £ " + total);		
		
	}
}

Open in new window

0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38775145
I think as much for your benefit as anyone else's here, you ought to try to run the code see what happens, then quote us any exceptions or logical errors in a stack trace copy here. Otherwise you are not going to get enough hands-on btl, and we end up doing all the coding instead. That isn't quite right.
0
 

Author Comment

by:Kevin_Coors
ID: 38777714
Hi Krakatoa

I agree with your principle here. However, since joining EE my coding has improved dramatically. I may post a few questions but the answers to those questions help me improve because I am learning by example and storing the info.

I am practising every day and I have answered over 120 questions although I have only posted for help on a very few on those questions. I'm not at college  I am learning by book and video. I am only using EE for assistance if I am in real difficulty and I am wasting to much time on one problem.

Thanks :)
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38777735
Difficult to see how you make the case for wasting time on it. Being in a hurry isn't going to help.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:Kevin_Coors
ID: 38777752
I mean being totally stumped on a problem. I'm not in a rush. However, some progress is better than no progress at all. If you dangle the carrot in front of the donkey then there's  a good chance the donkey will move. ;) If the donkey dosen't have the carrot he will stand his ground and be stubborn and unhappy
0
 

Author Comment

by:Kevin_Coors
ID: 38777788
Here is an example to reinforce my argument

Remember some time ago you posted this solution to a problem I was having

                totalYards = inches/yards;
            totalFeet = (inches-(totalYards*36))/12;
            totalInches = inches % 12;

Below is my adjustment on the solution so I could understand it and use it in the future I changed the second line of the code so I understood exactly what was happening

                totalYards = inches/yards;
             totalFeet = (inches % 36)/12;
            totalInches = inches % 12;

The assistance I am getting on EE is invaluable to me and I really appreciate it :)
0
 
LVL 16

Accepted Solution

by:
krakatoa earned 500 total points
ID: 38779004
import java.util.Scanner;

public class DinnerParty
{
	public static void main (String [] args)
	{
		//print out the menu
		//System.out.println ("1. Turkey and Ham \n2. Steak (€5 supplement)\n3. Nut roast (vegetarian €3 discount)\n4. Lasagne");

		Menu m = new Menu();
		

		for (int a=0;a<m.dishes.length;a++){
			
				System.out.printf("Dish  %s -- Price: %d -- Supplement:%d\n",m.dishes[a][0][0],m.dishes[a][0][1],m.dishes[a][0][2]);
		
		}
		
		System.out.println();//new line
		
		int partyNum;
		int choice = 0;
		int order;
		int count = 0;
		int total = 0;
		double mainCourse;
		int i = 0;
			
		Scanner kb = new Scanner(System.in);
		//get the user to enter the number of people in their party (Scanner class)
		System.out.println ("Please enter the number of people in your party");
		partyNum = kb.nextInt();
		
		//display number in party
		System.out.println("The number in your party is " + partyNum);
		
		// Read each member of the partys main course
				
		System.out.println();//new line
		
		System.out.println ("Please enter the Maincourse order for each of your party");
	
		for(i = 0; i < partyNum; i++)
		{
			choice = kb.nextInt();
			System.out.println();
			
			m.choix[(choice-1)]=(((Integer)m.choix[(choice-1)]).intValue())+1;
			
			System.out.println("Person " + (i+1) + " will have maincourse no: " +choice);
			
			count++;
		}
		
		//Count and display the number of each main course chosen
		 System.out.println("The total orders place are " + count);
		 	 
		// display the total cost of the booking

		for (int a=0;a<m.choix.length;a++){
				
				total += (((Integer)m.choix[a]).intValue()*(  ((Integer)m.dishes[a][0][1]).intValue()   ) ) ;
				int supp = ((Integer)m.dishes[a][0][2]).intValue();
				if(!(supp==0)){System.out.println("There is a "+supp+" adjustment on this dish. Program it into the code.");}
		}
		System.out.printf("Bill comes to  %s\n",total);

	}

   static class Menu {

	Object [][][] dishes = {{{"1 - Turkey & Ham",12,0}},{{"2 - Steak",15,5}},{{"3 - Nutroast",8,-3}},{{"4 - Lasagne",9,0}}};
	Integer[] choix = {0,0,0,0};
	

   }

 }

Open in new window

0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38780255
If you have any queries with the present code, ask me. My comments about you doing the coding were because in this 'lark', one of the best ways to learn is by trying and getting it (half) wrong. We've all been there.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38782040
There were unnecessary Integer casts in my previous code (which were there from using another method which I ditched). I didn't want you to think they were necessary, so here is the code without them, plus an extra bit to test again that the indexes are being accessed correctly.

import java.util.Scanner;

public class DinnerParty
{
	public static void main (String [] args)
	{
		
		Menu m = new Menu();
		
		System.out.println();//new line
		
		int partyNum;
		int choice = 0;
		int count = 0;
		int total = 0;
					
		Scanner kb = new Scanner(System.in);
		
		System.out.println ("Please enter the number of people in your party");
		partyNum = kb.nextInt();
		
		
		System.out.println("The number in your party is " + partyNum+"\n");
		
				
		System.out.println ("Please enter the Maincourse order for each of your party\n\n");


		for (int a=0;a<m.dishes.length;a++){
			
			System.out.printf("  %s -- Price: %d -- Supplement:%d\n",m.dishes[a][0][0],m.dishes[a][0][1],m.dishes[a][0][2]);
		
		}

	
		for(int i = 0; i < partyNum; i++){

			choice = kb.nextInt();
			System.out.println();
			
			m.choix[(choice-1)]=m.choix[(choice-1)]+1;
					
			System.out.println("Person " + (i+1) + " will have maincourse : " +m.dishes[choice-1][0][0]);
			
			count++;
		}
		
		
		 System.out.println("\nThe total number of orders placed is : " + count+"\n");
		 	 
		
		for (int a=0;a<m.choix.length;a++){
				
				total += ((m.choix[a])*(  ((Integer)m.dishes[a][0][1]).intValue()   ) ) ;
				int supp = ((Integer)m.dishes[a][0][2]).intValue();
				
				if(!(supp==0)&&m.choix[a]>0){total+= supp*m.choix[a];}
				if(!(supp==0)&&m.choix[a]<0){total+= supp*m.choix[a];}
		}

		
		for(int a=0;a<m.choix.length;a++){if(m.choix[a]>0){String s = m.choix[a]>1?" orders":" order";System.out.println(m.choix[a]+s+" for "+((String) m.dishes[a][0][0]).substring(((String)m.dishes[a][0][0]).indexOf("-")));}}		
		
		System.out.printf("\n%s\n","===========================");
		System.out.printf("Bill comes to  %s\n",total);
		System.out.printf("%s\n","===========================");
	}


   static class Menu {

	Object [][][] dishes = {{{"1 - Turkey & Ham",12,0}},{{"2 - Steak",15,5}},{{"3 - Nutroast",8,-3}},{{"4 - Lasagne",9,0}}};
	Integer[] choix = {0,0,0,0};
	

   }

 }

Open in new window

0
 

Author Comment

by:Kevin_Coors
ID: 38783396
Thanks Krakatoa

I always try and have a go at any java problem or question before I resort to trying to get assistance on it. The best way to learn is by doing. Thanks again. Below is any attempt I have made on the question

import java.util.Scanner;

public class DinnerParty
{
	public static void main (String [] args)
	{
		System.out.println ("1. Turkey and Ham \n2. Steak (€5 supplement)\n3. Nut roast (vegetarian €3 discount)\n4. Lasagne");
		System.out.println();//new line
		
		int partyNum;
		int choice = 0;
		int order = 0;
		int count = 0;
		int total = 0;
		double[] dinners = { 22.00,27.00,19.00,22.00};
		int i = 0;
	  
		Scanner kb = new Scanner(System.in);
		//get the user to enter the number of people in their party (Scanner class)
		System.out.println ("Please enter the number of people in your party");
		partyNum = kb.nextInt();
		
		//display number in party
		System.out.println("The number in your party is " + partyNum);
		
		// Read each member of the partys main course
		System.out.println();//new line
		
		System.out.println ("Please enter the Maincourse order for each of your party");
		
			for(i = 1; i <= partyNum; i++)
				{
				  choice = kb.nextInt(); 
			 	  kb.nextLine(); // consume the next line from the scanner
				  
				  System.out.println("Person " + i + " will have maincourse no: " +choice);
				  total += dinners[choice];  // look up the cost of this choice and add it to the bill
			     System.out.println("Your maincourse cost is £"+ dinners[choice]);  // inform the diner
				  count++;
				}
				
			 //Count and display the number of each main course chosen
	       System.out.println("The total orders placed was " + count);
			 // Display the total cost of the order
			 System.out.println("The total cost of the orders placed is £" + total);		
		
	}
}

Open in new window

0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38783470
That's fine; but I would study the code I posted and compare it to what you are doing. You are welcome to ask (even in this "dead" question) anything about the code that you want explanation on.

One thing then - you should always get used to starting "for" loops with an index of 0 - zero. This may seem to make life more difficult to start with, but it just means getting used to it. The main reason is that arrays always have their first element indexed to 0, and so using 0 in your loops will help avoid missing that point. And by the way, you do not seem to have taken the supplements into account in your code. l;)
0
 

Author Comment

by:Kevin_Coors
ID: 38783537
Thanks

Yeah I seen some code yesterday where some code in a do while had a + 1 added to it. I understand that this was so that all the results started with a 1 and not a zero.

Yes I left out the supplements. I was really struggling with how I could store the multiple orders and using an array was the answer :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now