Last active
August 29, 2015 13:55
-
-
Save Hulzenga/8761929 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class CookingHelper | |
{ | |
// this variable belongs inside the method | |
// private static String ingredients = "Couldn't find this recipe."; | |
/* | |
* the cookbook on the other hand remains the same during each method call, | |
* so this bit should be defined outside the method. Oh and since you only | |
* have 2 cookbook entries you should keep the cookBook array to that same | |
* size | |
*/ | |
static String[] cookBook = new String[2]; | |
static String[] cookBookName = new String[2]; | |
// this is a Static Initialization Block, usefull for populating the field | |
// of static variables | |
static { | |
String riceName = "rice"; | |
String rice = "1 cup water, 1 cup rice, 1 pinch salt, 1 pinch pepper"; | |
String spagettiName = "spagetti"; | |
String spagetti = "spagetti, tomato sauce"; | |
cookBook[0] = rice; | |
cookBookName[0] = riceName; | |
cookBook[1] = spagetti; | |
cookBookName[1] = spagettiName; | |
} | |
public static String cookingDecision(String food) | |
{ | |
// using a for loop like this you can walk over all the cookBook entries | |
// and you don't have to worry about changing the value of the cookBook | |
// length in 2 places when you add new cookBook entries | |
for (int count = 0; count < cookBook.length; count++) { | |
if (cookBookName[count].contains(food)) | |
{ | |
//if a recipe contains the entry food return the recipe | |
return cookBook[count]; | |
} | |
} | |
/* | |
* the default return value. You could also define this outside of the | |
* method, but then you would want a constant value which you don not | |
* edit (i.e. public static final String NO_INGREDIENT_FOUND = | |
* "Couldnt find this recipe") | |
*/ | |
return "Couldnt find this recipe"; | |
} | |
public static void main(String[] args) | |
{ | |
Scanner input = new Scanner(System.in); | |
System.out.println("What do you want to cook today?"); | |
String food = input.nextLine(); | |
String recipe = cookingDecision(food); | |
System.out.println(recipe); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment