Difference between revisions of "Creating a grocery list"

From CompSciWiki
Jump to: navigation, search
Line 22: Line 22:
 
|SideSectionTitle=More with Arrays
 
|SideSectionTitle=More with Arrays
 
|SideSection=
 
|SideSection=
[[Image:Wiki_method01.jpg|float]]
+
[[Image:Wiki_method01.jpg|center]]
  
 
|Solution=
 
|Solution=

Revision as of 12:47, 6 April 2010

Back to the Program-A-Day homepage

Problem

Create a grocery list. Prompt the user for the number of items and the quantity. Then print the list of items.

Example Output

Enter the number of items for the list: 3
Next item:bacon
Item Quantity:1
Next item:eggs
Item Quantity:12
Next item:apples
Item Quantity:4


Grocery List
------------
1 bacon
12 eggs
4 apples
 

More with Arrays

Wiki method01.jpg

Solution

Prompt the user for the number of items:

//setup a BufferedReader to read from the console
BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in) );

int listSize = 0; //the number of items for the grocery list

//read in a value and try casting it to an integer
//Java requires you catch any exceptions that may arise 
System.out.print ("Enter the number of items for the list: ");
try
{
	String tempListSize = stdin.readLine();
	listSize = Integer.parseInt( tempListSize );
}
catch(Exception ex)
{
	System.out.println("Input error");
	System.exit(1);
}

Next, loop up to the inputted value prompting the user for grocery list items

//Create and array of strings, size listSize
String[] groceryList     = new String[listSize];
int[]    groceryQuantity = new int[listSize];

//loop from zero to the size of the array
for( int i = 0; i < groceryList.length; i++ )
{
	//Java requires you to catch any exceptions
	try
	{
		System.out.print( "Next item:" );
		groceryList[ i ] = stdin.readLine();
		System.out.print( "Item Quantity:" );
		groceryQuantity[ i ] = Integer.parseInt( stdin.readLine() );
	}
	catch(Exception ex)
	{
		System.out.println("Input error");
		System.exit(1);
	}
}

Last step is to print the list out.

//Print a header for the list
System.out.println( "\n\nGrocery List" );
System.out.println( "------------" );

//loop through and print out the list items
for( int i = 0; i < groceryList.length; i++ )
{
	System.out.println( groceryQuantity[ i ] + " " + groceryList[ i ] );
}

Code

Solution Code

Back to the Program-A-Day homepage