diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/AddIngredientController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/AddIngredientController.java index df9e639d1c029eb0033766bc3184e722716ba0d0..2517d58789ec417759b0a9eb0ac51998ab83e96f 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/AddIngredientController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/AddIngredientController.java @@ -102,12 +102,12 @@ public class AddIngredientController implements Initializable { @FXML void addToFridge() throws IOException { FoodItem item; - try{ + try { item = FoodItem.valueOf(listView.getSelectionModel() - .getSelectedItem().replace(" ", "_").toUpperCase()); + .getSelectedItem().replace(" ", "_").toUpperCase()); } catch (NullPointerException e) { - item = null; - return; + item = null; + return; } IngredientsAtHand ingredientsAtHand = FileHandler.readIngredientsAtHand(filePath + "Fridge"); diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/AllRecipesController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/AllRecipesController.java index 51e6a2a58db49b696009cf6e5a2ba8292b8e7678..2d030f06e857d84b9aec656307b8326af1c98564 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/AllRecipesController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/AllRecipesController.java @@ -161,8 +161,6 @@ public class AllRecipesController implements Initializable { Scene scene = new Scene(root); stage.setScene(scene); stage.show(); - } else { - System.out.println("The selected recipe is null."); } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/BudgetController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/BudgetController.java index c2b6156d15b377cfaa4af516fdb99888d6635a83..21e230e521b1020786b2266dfadd042e817cce4a 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/BudgetController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/BudgetController.java @@ -127,12 +127,11 @@ public class BudgetController extends FinanceController { //Refresh pie charts only if the budget is old if (!FileHandlingBudget.isNewBudget( - filePath + "/" + FileHandlingSelectedBudget + filePath + "/" + FileHandlingSelectedBudget .readSelectedBudget(filePath + "/SelectedBudget") + "/Budget")) { refreshPieChart(); } } catch (IOException ioe) { - ioe.printStackTrace(); showErrorDialogBox(ioe.getMessage(), ioe.getMessage(), ioe.getMessage()); } @@ -169,7 +168,7 @@ public class BudgetController extends FinanceController { //Only adds the budget data for chosen categories to the pie chart for (ExpenseCategory category : chosenCategories) { - budgetData.add(new Data( category.label, + budgetData.add(new Data(category.label, general.getBudgetItem(category).getBudgetAmount())); } return budgetData; @@ -345,8 +344,8 @@ public class BudgetController extends FinanceController { @Override public void saveDataToFile() throws IOException { FileHandlingBudget.writeGeneralBudgetToFile( - filePath + "/" + FileHandlingSelectedBudget - .readSelectedBudget( filePath + "/SelectedBudget") + "/Budget", general); + filePath + "/" + FileHandlingSelectedBudget + .readSelectedBudget(filePath + "/SelectedBudget") + "/Budget", general); } /** @@ -387,7 +386,7 @@ public class BudgetController extends FinanceController { //Adds unused categories to the table general.addUnusedCategories(); updateBudgetRegister(FileHandlingSelectedBudget - .readSelectedBudget(filePath + "/SelectedBudget")); + .readSelectedBudget(filePath + "/SelectedBudget")); //Always saving the data when switching to main menu saveDataToFile(); @@ -421,7 +420,6 @@ public class BudgetController extends FinanceController { stage.show(); } catch (Exception ioe) { - ioe.printStackTrace(); showErrorDialogBox("Loading error", "Error in loading", "Could not load" + " FXML file in: " + loader.getLocation()); } diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/CreateBudgetController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/CreateBudgetController.java index 41b6d0425ba7f50e1bda34d1fd76e747e39a17c3..dfa128b107cf43f7d7bcf9bf29730635b5dba004 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/CreateBudgetController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/CreateBudgetController.java @@ -173,8 +173,6 @@ public class CreateBudgetController { "Budget"); } catch (IOException ioe) { empty = false; - System.out.println(ioe.getMessage()); - ioe.printStackTrace(); showErrorMsgBox(ioe.getMessage(), ioe.getMessage(), ioe.getMessage()); } return empty; @@ -188,7 +186,6 @@ public class CreateBudgetController { * @param budgetName The name of the budget. */ public void updateCurrentFile(String currentMonth, String budgetName) { - System.out.println(currentMonth + budgetName); try { FileHandlingSelectedBudget.updateSelectedBudget(currentMonth + budgetName, diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/FinanceController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/FinanceController.java index dfc9714f788d60cad5ab9fedaf6f3c7c023a5f7e..185e2cc21107002a502515241e0693c0c5066a97 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/FinanceController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/FinanceController.java @@ -106,8 +106,6 @@ public abstract class FinanceController { */ public GeneralBudget loadBudgetDataFromFile(String fileDestination) throws IOException { //Instantiate new budget - System.out.println("this is just beofre isempty"); - System.out.println(fileDestination); if (FileHandlingBudget.isEmpty(fileDestination)) { general = new GeneralBudget(1000); } else { //Load previous budget @@ -137,7 +135,6 @@ public abstract class FinanceController { incomeRegister = FileHandling.readIncomeRegisterFromFile(fileDestination); } } catch (IOException ioe) { - ioe.printStackTrace(); showErrorDialogBox("File reading error", "Error in reading from file", "Could not" + "read the IncomeRegister from file"); } diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/FirstMenuController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/FirstMenuController.java index 3e8742f141c4bf6208b42c7c84254ecd5d23ded1..436e0aef6d204e05c05851edd03f172a6996e653 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/FirstMenuController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/FirstMenuController.java @@ -1,7 +1,7 @@ package no.ntnu.idatt1002.demo.controller; -import java.io.*; - +import java.io.File; +import java.io.IOException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; @@ -17,7 +17,6 @@ import javafx.stage.Screen; import javafx.stage.Stage; import no.ntnu.idatt1002.demo.data.budget.FileHandlingSelectedBudget; import no.ntnu.idatt1002.demo.data.economics.Income; -import no.ntnu.idatt1002.demo.data.recipes.FileHandler; import no.ntnu.idatt1002.demo.data.recipes.RecipeRegister; /** @@ -30,6 +29,7 @@ public class FirstMenuController { private RecipeRegister startRegister; //TODO: + /** * Initializes as soon as the scene is loaded. */ @@ -57,22 +57,6 @@ public class FirstMenuController { if (!recipes.exists()) { recipes.mkdirs(); } - - /* File recipesFile = new File(buddyPath + "/recipes/Recipes.register"); - if (!recipesFile.exists()) { - System.out.printf("\"The file must be filled\""); - try { - recipesFile.createNewFile(); - System.out.printf("Going to fill the register"); - - recipesFile.createNewFile(); - - } catch (IOException e) { - throw new RuntimeException(e); - } - }*/ - - } /** @@ -184,7 +168,6 @@ public class FirstMenuController { switchChosenBudget(event); } } catch (IOException ioe) { - ioe.printStackTrace(); showErrorDialogBox("Loading error", "Could not switch to main menu", ""); } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/IncomeExpenseController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/IncomeExpenseController.java index 97c8bc9b8ecfccd6292ade427f4d547a4f139133..32a08415ffdc08c8cf87e4d79c5821ebda6aa9c4 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/IncomeExpenseController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/IncomeExpenseController.java @@ -2,13 +2,8 @@ package no.ntnu.idatt1002.demo.controller; import java.io.IOException; import java.time.LocalDate; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; - -import javafx.beans.Observable; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; @@ -31,7 +26,6 @@ import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Modality; import javafx.stage.Stage; -import javafx.util.Callback; import no.ntnu.idatt1002.demo.data.budget.FileHandlingBudget; import no.ntnu.idatt1002.demo.data.budget.FileHandlingSelectedBudget; import no.ntnu.idatt1002.demo.data.economics.Expense; @@ -159,7 +153,7 @@ public class IncomeExpenseController extends FinanceController { //Initialize registers incomeRegister = loadIncomeDataFromFile( filePath + FileHandlingSelectedBudget - .readSelectedBudget( filePath + "SelectedBudget") + "/Income"); + .readSelectedBudget(filePath + "SelectedBudget") + "/Income"); expenseRegister = loadExpenseDataFromFile( filePath + FileHandlingSelectedBudget .readSelectedBudget(filePath + "SelectedBudget") + "/Expense"); @@ -230,9 +224,9 @@ public class IncomeExpenseController extends FinanceController { private ObservableList<PieChart.Data> createExpensePieChart() { return FXCollections.observableArrayList(Arrays.stream(ExpenseCategory.values()) - .filter(exp -> expenseRegister.getExpenseByCategory(exp).getTotalSum() > 0) - .map(exp -> new Data(exp.label,expenseRegister.getExpenseByCategory(exp).getTotalSum())) - .toList()); + .filter(exp -> expenseRegister.getExpenseByCategory(exp).getTotalSum() > 0) + .map(exp -> new Data(exp.label, expenseRegister.getExpenseByCategory(exp).getTotalSum())) + .toList()); } /** @@ -244,9 +238,9 @@ public class IncomeExpenseController extends FinanceController { private ObservableList<PieChart.Data> createIncomePieChart() { return FXCollections.observableArrayList(Arrays.stream(IncomeCategory.values()) - .filter(in -> incomeRegister.getIncomeByCategory(in).getTotalSum() > 0) - .map(in -> new Data( in.label, incomeRegister.getIncomeByCategory(in).getTotalSum())) - .toList()); + .filter(in -> incomeRegister.getIncomeByCategory(in).getTotalSum() > 0) + .map(in -> new Data(in.label, incomeRegister.getIncomeByCategory(in).getTotalSum())) + .toList()); } /** @@ -269,7 +263,6 @@ public class IncomeExpenseController extends FinanceController { @Override public void handleAddBtn(javafx.event.ActionEvent event) { int sizeBf = (expenseRegister.getItems().size() + incomeRegister.getItems().size()); - System.out.printf("handleAdd button"); if (event.getSource() == addIncome) { handleAddIncome(); @@ -638,7 +631,6 @@ public class IncomeExpenseController extends FinanceController { stage.setResizable(false); stage.show(); } catch (IOException ioe) { - ioe.printStackTrace(); showErrorDialogBox("Loading error", "Error in loading", "Could not save" + "to file"); } diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/MainMenuController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/MainMenuController.java index 8fd2f2b5b82392d72996c0252dd475109cca0ae5..050345298cbd7ce3571d79cb103f80fed4704c00 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/MainMenuController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/MainMenuController.java @@ -107,7 +107,6 @@ public class MainMenuController { .readSelectedBudget(filePath + "SelectedBudget") + "/Budget"); overview = new Overview(incomeRegister, expenseRegister, generalBudget); } catch (IOException | IllegalArgumentException ioe) { - ioe.printStackTrace(); showErrorDialogBox(ioe.getMessage(), ioe.getMessage(), ioe.getMessage()); } @@ -245,7 +244,6 @@ public class MainMenuController { public GeneralBudget loadBudgetDataFromFile(String fileDestination) throws IOException { //Instantiate new budget if (FileHandlingBudget.isEmpty(fileDestination)) { - System.out.println("hey from MainMenuController"); generalBudget = new GeneralBudget(1000); } else { //Load previous budget try { diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/SelectBudgetController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/SelectBudgetController.java index 73bc45c0fdf2efe590dcf4be1aa70302326c029f..6b0de75a7f7e9a7a91ab810bdfd16d7041ac429c 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/SelectBudgetController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/SelectBudgetController.java @@ -64,9 +64,8 @@ public class SelectBudgetController { budgetRegister = FileHandlingBudgetArchive.readBudgetArchive(filePath + "/Archive"); } } catch (IOException ioe) { - ioe.printStackTrace(); + showErrorDialogBox(ioe.getMessage(), ioe.getMessage(), ioe.getMessage()); } - System.out.println("budget register is: " + budgetRegister); ObservableList<String> budgetList = FXCollections.observableList( budgetRegister.getBudgetNames()); budgetListView.setItems(budgetList); diff --git a/src/main/java/no/ntnu/idatt1002/demo/controller/SuggestRecipesController.java b/src/main/java/no/ntnu/idatt1002/demo/controller/SuggestRecipesController.java index 25769b3ae3780c23cff269e843da8ad28175dde1..524662d110c496fa8a4c604b43905ae648f35c35 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/controller/SuggestRecipesController.java +++ b/src/main/java/no/ntnu/idatt1002/demo/controller/SuggestRecipesController.java @@ -1,6 +1,7 @@ package no.ntnu.idatt1002.demo.controller; -import java.io.*; +import java.io.File; +import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Optional; @@ -85,7 +86,7 @@ public class SuggestRecipesController implements Initializable { filePath = path + "/BudgetBuddyFiles/recipes/"; File atHand = new File(filePath + "Fridge.register"); - if(!atHand.exists()){ + if (!atHand.exists()) { try { atHand.createNewFile(); } catch (IOException e) { @@ -94,7 +95,7 @@ public class SuggestRecipesController implements Initializable { } File recipesFile = new File(filePath + "Recipes.register"); - if(!recipesFile.exists()){ + if (!recipesFile.exists()) { try { recipesFile.createNewFile(); @@ -105,7 +106,6 @@ public class SuggestRecipesController implements Initializable { } } - try { readIngredientsAtHand(); } catch (IOException e) { @@ -189,8 +189,8 @@ public class SuggestRecipesController implements Initializable { * upon updating to prevent then from layering on top of each other. */ private void setRecipeTiles() { - int NUMBER_OF_TILES = 4; - ArrayList<Recipe> recipes = recipeRegister.pickBestFits(NUMBER_OF_TILES, ingredientsAtHand); + int numberOfTiles = 4; + ArrayList<Recipe> recipes = recipeRegister.pickBestFits(numberOfTiles, ingredientsAtHand); int i = 0; int j = 0; diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudget.java b/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudget.java index b54d9ce171a89b5d97ab84f3b5b753039fab1d3f..4fed36b3bda7997f544dfb6edee1babba140e743 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudget.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudget.java @@ -33,7 +33,6 @@ public class FileHandlingBudget { try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileDestination + fileType))) { bw.write(generalBudget.toString()); } catch (IOException ex) { - ex.printStackTrace(); throw new IOException("Error writing to file: " + fileDestination); } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudgetArchive.java b/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudgetArchive.java index f3a85b1d67e8035b0e34e008661452f8c9788e5c..b0251c0cf34efd01adc185c1b466c6584b784618 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudgetArchive.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingBudgetArchive.java @@ -1,23 +1,15 @@ package no.ntnu.idatt1002.demo.data.budget; -import java.io.*; - -//Set titler på hvert vindu - kan gjøres i switch scene -//Dynamic days left -//teste klasser med lav coverage -//Close program properly -//close button i first menu -//remove printstackstraces -//En delete funksjon i select old budget -//Endre pakkenavn -//Public vs private metoder må sjekkes -// FIKSE TRY CATCHES I ALLE METODENE!!!!!!!!!! +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; /** - * Class that handles the reading and writing to the budget archive file, - * which contains all existing budget projects. New budgets are added to the archive - * through this class. - + * Class that handles the reading and writing to the budget archive file, which contains all + * existing budget projects. New budgets are added to the archive through this class. + * * @author Harry Linrui Xu * @since 19.04.2023 */ @@ -27,16 +19,14 @@ public class FileHandlingBudgetArchive { /** * Method for writing (adding) a budget register to the archive. - - * @param budgetNames The budget register. + * + * @param budgetNames The budget register. * @param fileDestination The file destination in resources. * @throws IOException if an input or output exception occurred. */ public static void writeBudgetRegisterToArchive(BudgetRegister budgetNames, String fileDestination) throws IOException { - File file = new File(String.format("%s%s", fileDestination, fileType)); - try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileDestination + fileType))) { bw.write(budgetNames.toString()); } catch (IOException ioe) { @@ -45,9 +35,9 @@ public class FileHandlingBudgetArchive { } /** - * Checks if the budget register in the archive contains any budget names. - * In other words, if it is empty. - + * Checks if the budget register in the archive contains any budget names. In other words, if it + * is empty. + * * @param fileDestination The file destination in resources. * @return True, if only "null" is read. Else, returns false. * @throws IOException if an input or output exception occurred. @@ -60,8 +50,8 @@ public class FileHandlingBudgetArchive { /** * Method for reading the budget register from the archive. + * * @param fileDestination The file destination in resources. - * @return The budget register that is read from file. * @throws IOException if an input or output exception occurred. */ @@ -75,7 +65,6 @@ public class FileHandlingBudgetArchive { String nextLine = br.readLine(); while ((line = nextLine) != null) { - System.out.println(line); nextLine = br.readLine(); budgetName = line; diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingSelectedBudget.java b/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingSelectedBudget.java index b0dd7c19e2ebe72465350675b2173c0d698b5682..7c8e58adcbdf3f550700ca930c71b3fa0259f93e 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingSelectedBudget.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/budget/FileHandlingSelectedBudget.java @@ -15,6 +15,7 @@ import java.io.IOException; * @since 19.04.2023 */ public class FileHandlingSelectedBudget { + private static final String selectedBudgetFileType = ".current"; private static final String registerFileType = ".register"; private static final String budgetFileType = ".budget"; @@ -29,7 +30,7 @@ public class FileHandlingSelectedBudget { public static String readSelectedBudget(String fileDestination) throws IOException { System.out.println("Reading current file: " + fileDestination - + selectedBudgetFileType); + + selectedBudgetFileType); try (BufferedReader br = new BufferedReader(new FileReader(fileDestination + selectedBudgetFileType))) { @@ -49,17 +50,6 @@ public class FileHandlingSelectedBudget { public static void updateSelectedBudget(String budgetName, String fileDestination) throws IOException { - System.out.print("Updating current file to: " + fileDestination - + selectedBudgetFileType + "->" + budgetName); - -/* - File file = new File(String.format("%s%s", fileDestination, selectedBudgetFileType)); -*/ - -/* if (!file.exists()){ - file.createNewFile(); - }*/ - try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileDestination + selectedBudgetFileType))) { bw.write(budgetName); @@ -96,7 +86,8 @@ public class FileHandlingSelectedBudget { * @throws IOException if an input or output exception occurred. */ public static boolean isSelectedBudgetEmpty(String fileDestination) throws IOException { - try (BufferedReader br = new BufferedReader(new FileReader(fileDestination + selectedBudgetFileType))) { + try (BufferedReader br = new BufferedReader( + new FileReader(fileDestination + selectedBudgetFileType))) { return br.readLine() == null; } } @@ -146,10 +137,7 @@ public class FileHandlingSelectedBudget { * @throws IOException if an input or output exception occurred. */ public static boolean createNewIncomeFile(String budgetDestination, String incomeFileTitle) - // TODO: Se over throws IOException { - System.out.println("Income filePath: " + budgetDestination + "/" + incomeFileTitle - + registerFileType); File incomeFile = new File( budgetDestination + "/" + incomeFileTitle + registerFileType); return incomeFile.createNewFile(); @@ -167,8 +155,6 @@ public class FileHandlingSelectedBudget { public static boolean createNewExpenseFile(String budgetDestination, String expenseFileTitle) throws IOException { - System.out.println("Expense filePath: " + budgetDestination + "/" + expenseFileTitle - + registerFileType); File expenseFile = new File( budgetDestination + "/" + expenseFileTitle + registerFileType); return expenseFile.createNewFile(); diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/economics/FileHandling.java b/src/main/java/no/ntnu/idatt1002/demo/data/economics/FileHandling.java index 23cc7c2f55502c0bfef617de94bb45041fa51351..c93b908a51b792c4e5311c32c36327e997299f28 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/economics/FileHandling.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/economics/FileHandling.java @@ -69,7 +69,8 @@ public class FileHandling { * @return the IncomeRegister from the file. * @throws IOException if an input or output exception occurred. */ - public static IncomeRegister readIncomeRegisterFromFile(String fileDestination) throws IOException { + public static IncomeRegister readIncomeRegisterFromFile(String fileDestination) + throws IOException { IncomeRegister incomeRegister = new IncomeRegister(); LocalDate date = null; String description = ""; @@ -118,7 +119,8 @@ public class FileHandling { * @return the ExpenseRegister from the file. * @throws IOException if an input or output exception occurred */ - public static ExpenseRegister readExpenseRegisterFromFile(String fileDestination) throws IOException { + public static ExpenseRegister readExpenseRegisterFromFile(String fileDestination) + throws IOException { ExpenseRegister expenseRegister = new ExpenseRegister(); LocalDate date = null; String description = ""; diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java index 1c9cd2ce43a6a62cf3824d7cfdee5d33edd784a8..ea903b77271e4cfd333cce093b9421e0c44e5e78 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java @@ -1,227 +1,233 @@ package no.ntnu.idatt1002.demo.data.recipes; -import java.io.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; import java.util.List; import java.util.Scanner; /** - * The FileHandler class is a static class that handles reading and writing to the .register files for storing - * dinner recipes and ingredients at hand. Files of this class are stored at src/main/resources/recipes. + * The FileHandler class is a static class that handles reading and writing to the .register files + * for storing dinner recipes and ingredients at hand. Files of this class are stored at + * src/main/resources/recipes. * * @author hannesofie */ public class FileHandler { - private static final String fileType = ".register"; - - /** - * The method takes a RecipeRegister object and a String as parameters. The recipe register is then written - * to a file named after the provided string, with the file-type ".register" in the /main/recourses/recipes folder. - * The file is written at the following format and is only sensitive to new-lines within the instructions-String: - * # Recipe name - * - Ingredient 1 | amount | unit - * - Ingredient 2 | amount | unit - * - ... - * Instructions - * An IllegalArgumentException is thrown if the recipe register is null. IOExceptions may occur upon writing to - * file, in which case the stacktrace is printed to terminal. - * - * @param recipeRegister A recipe register object that is to be written to file. - * @param fileDestination The path and title by which to name the .register-file. - */ - public static void writeRegister(RecipeRegister recipeRegister, String fileDestination) { - if (recipeRegister == null) { - throw new IllegalArgumentException("Only a valid register object can be written to file."); - } - - try (FileWriter fileWriter = new FileWriter(fileDestination + fileType)) { - recipeRegister.getRecipes().forEach((recipe) -> - { - try { - fileWriter.write(formatRecipe(recipe).toString()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - ); - - } catch (IOException e) { - e.printStackTrace(); - } + private static final String fileType = ".register"; + + /** + * The method takes a RecipeRegister object and a String as parameters. The recipe register is + * then written to a file named after the provided string, with the file-type ".register" in the + * /main/recourses/recipes folder. The file is written at the following format and is only + * sensitive to new-lines within the instructions-String: # Recipe name - Ingredient 1 | amount | + * unit - Ingredient 2 | amount | unit - ... Instructions An IllegalArgumentException is thrown if + * the recipe register is null. IOExceptions may occur upon writing to file, in which case the + * stacktrace is printed to terminal. + * + * @param recipeRegister A recipe register object that is to be written to file. + * @param fileDestination The path and title by which to name the .register-file. + */ + public static void writeRegister(RecipeRegister recipeRegister, String fileDestination) { + if (recipeRegister == null) { + throw new IllegalArgumentException("Only a valid register object can be written to file."); } - /** - * The method supports the method for writing a recipe register to file by taking in a single recipe object - * and return it as a String at the correct format for storage. - * - * @param recipe A recipe object to format into a String. - * @return A String representation of the recipe at the specified format for file storage. - */ - public static StringBuilder formatRecipe(Recipe recipe) { - StringBuilder sb = new StringBuilder(); - sb.append("# ") - .append(recipe.getName()) - .append("\n") - .append(formatIngredientList(recipe.getIngredientList())) - .append("\n") - .append(recipe.getInstructions()) - .append("\n\n"); - return sb; - } + try (FileWriter fileWriter = new FileWriter(fileDestination + fileType)) { + recipeRegister.getRecipes().forEach((recipe) -> { + try { + fileWriter.write(formatRecipe(recipe).toString()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + ); - /** - * The method supports the 'formatRecipe' method by receiving a list of ingredient objects and returning a - * String at the correct format for the writing to file. - * - * @param ingredientList A list of ingredients to be formatted into a String. - * @return A String of the ingredients at the correct format for writing to file. - */ - public static StringBuilder formatIngredientList(List<RecipeIngredient> ingredientList) { - StringBuilder sb = new StringBuilder(); - - ingredientList.forEach((ingredient) -> sb.append("- ") - .append(ingredient.getFoodType()) - .append(" | ") - .append(ingredient.getAmount()) - .append(" | ") - .append(ingredient.getUnit()) - .append("\n")); - return sb; + } catch (IOException e) { + throw new IllegalArgumentException(e); } - - /** - * The method reads a recipe register from file and returns the recipe register object. The title of the file - * is provided as a String. If the file doesn't exist, a message is written to the terminal and null is returned - * instead of a recipe register. Each recipe is separated by a '#'-sign and passed on to the method 'readRecipe' - * that reads and returns each Recipe object for the register. - * - * @param fileDestination Title of the .register file at which the recipe register is saved. - * @return A recipe register object read from file. - */ - public static RecipeRegister readRecipeRegister(String fileDestination) throws IOException { - System.out.println(fileDestination); - File file = new File(fileDestination + fileType); - - //TODO: Provide 'starter' for recipes - - - RecipeRegister register = new RecipeRegister(); - - try (Scanner sc = new Scanner(file)) { - sc.useDelimiter("#"); - String line; - - while (sc.hasNext()) { - line = sc.next(); - if (!line.isBlank()) { - register.addRecipe(readRecipe(line)); - } - } - } catch (FileNotFoundException e) { - System.out.println("The file was not found."); - return null; + } + + /** + * The method supports the method for writing a recipe register to file by taking in a single + * recipe object and return it as a String at the correct format for storage. + * + * @param recipe A recipe object to format into a String. + * @return A String representation of the recipe at the specified format for file storage. + */ + public static StringBuilder formatRecipe(Recipe recipe) { + StringBuilder sb = new StringBuilder(); + sb.append("# ") + .append(recipe.getName()) + .append("\n") + .append(formatIngredientList(recipe.getIngredientList())) + .append("\n") + .append(recipe.getInstructions()) + .append("\n\n"); + return sb; + } + + /** + * The method supports the 'formatRecipe' method by receiving a list of ingredient objects and + * returning a String at the correct format for the writing to file. + * + * @param ingredientList A list of ingredients to be formatted into a String. + * @return A String of the ingredients at the correct format for writing to file. + */ + public static StringBuilder formatIngredientList(List<RecipeIngredient> ingredientList) { + StringBuilder sb = new StringBuilder(); + + ingredientList.forEach((ingredient) -> sb.append("- ") + .append(ingredient.getFoodType()) + .append(" | ") + .append(ingredient.getAmount()) + .append(" | ") + .append(ingredient.getUnit()) + .append("\n")); + return sb; + } + + /** + * The method reads a recipe register from file and returns the recipe register object. The title + * of the file is provided as a String. If the file doesn't exist, a message is written to the + * terminal and null is returned instead of a recipe register. Each recipe is separated by a + * '#'-sign and passed on to the method 'readRecipe' that reads and returns each Recipe object for + * the register. + * + * @param fileDestination Title of the .register file at which the recipe register is saved. + * @return A recipe register object read from file. + */ + public static RecipeRegister readRecipeRegister(String fileDestination) throws IOException { + System.out.println(fileDestination); + File file = new File(fileDestination + fileType); + + //TODO: Provide 'starter' for recipes + + RecipeRegister register = new RecipeRegister(); + + try (Scanner sc = new Scanner(file)) { + sc.useDelimiter("#"); + String line; + + while (sc.hasNext()) { + line = sc.next(); + if (!line.isBlank()) { + register.addRecipe(readRecipe(line)); } - return register; + } + } catch (FileNotFoundException e) { + System.out.println("The file was not found."); + return null; } - - /** - * The method supports the readRecipeRegister method by receiving a string containing the information needed to - * create one specific recipe object. The method reads the needed information from this String and returns - * the Recipe object based on this. The beginning of each ingredient line is recognized by a hyphen ('-'), while - * the instructions are all lines, including internal new-lines, that do not start with a hyphen. - * - * @param fileDestination A String representation of the path and recipe to read from file. - * @return A recipe object based on the provided string representation. - */ - public static Recipe readRecipe(String fileDestination) { - Scanner sc = new Scanner(fileDestination); - - System.out.println(fileDestination); - Recipe recipe; - String instructions = "None"; - String recipeName = sc.nextLine().strip(); - StringBuilder sb = new StringBuilder(); - - String line; - recipe = new Recipe(recipeName, instructions); - - while (sc.hasNextLine()) { - line = sc.nextLine(); - - if (line.startsWith("-")) { - String[] ingredientParts = line.split("\\|"); - - FoodItem ingredientType = FoodItem.valueOf(ingredientParts[0].replaceFirst("-", "").strip()); - double ingredientAmount = Double.parseDouble(ingredientParts[1].strip()); - MeasuringUnit ingredientUnit = MeasuringUnit.valueOf(ingredientParts[2].strip()); - - recipe.addIngredient(ingredientType, ingredientAmount, ingredientUnit); - } else { - sb.append(line).append("\n"); - } - } - recipe.setInstructions(String.valueOf(sb).strip()); - return recipe; + return register; + } + + /** + * The method supports the readRecipeRegister method by receiving a string containing the + * information needed to create one specific recipe object. The method reads the needed + * information from this String and returns the Recipe object based on this. The beginning of each + * ingredient line is recognized by a hyphen ('-'), while the instructions are all lines, + * including internal new-lines, that do not start with a hyphen. + * + * @param fileDestination A String representation of the path and recipe to read from file. + * @return A recipe object based on the provided string representation. + */ + public static Recipe readRecipe(String fileDestination) { + Scanner sc = new Scanner(fileDestination); + + System.out.println(fileDestination); + Recipe recipe; + String instructions = "None"; + String recipeName = sc.nextLine().strip(); + StringBuilder sb = new StringBuilder(); + + String line; + recipe = new Recipe(recipeName, instructions); + + while (sc.hasNextLine()) { + line = sc.nextLine(); + + if (line.startsWith("-")) { + String[] ingredientParts = line.split("\\|"); + + FoodItem ingredientType = FoodItem.valueOf( + ingredientParts[0].replaceFirst("-", "").strip()); + double ingredientAmount = Double.parseDouble(ingredientParts[1].strip()); + MeasuringUnit ingredientUnit = MeasuringUnit.valueOf(ingredientParts[2].strip()); + + recipe.addIngredient(ingredientType, ingredientAmount, ingredientUnit); + } else { + sb.append(line).append("\n"); + } } - - - /** - * The method takes in an IngredientsAtHand object and writes it to a .register-file with the provided - * String as title. The file contains no other information than a simple list of FoodItem constants - * separated by new-line. The resulting file is stored at /main/recourses/recipes/. - * An IllegalArgumentException is thrown if the ingredients at hand object is null. - * IOExceptions may occur upon writing to file, in which case the stacktrace is printed to terminal. - * - * @param ingredientsAtHand An IngredientsAtHand object that holds a collection of constants of the - * FoodItem enum class. - * @param fileDestination The path and title by which to name the file that the ingredients at hand are written to. - * @throws IOException if an input or output error occurs. - */ - public static void writeIngredientsAtHand(IngredientsAtHand ingredientsAtHand, String fileDestination) throws IOException { - StringBuilder sb = new StringBuilder(); - System.out.println("Write IAH: " + fileDestination + fileType); - - try (FileWriter fileWriter = new FileWriter(fileDestination + fileType)) { - if (ingredientsAtHand == null) { - fileWriter.write(""); - }else { - ingredientsAtHand.getIngredientsAtHand().forEach((ingredient) -> sb.append(ingredient).append("\n")); - try { - fileWriter.write(String.valueOf(sb)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } + recipe.setInstructions(String.valueOf(sb).strip()); + return recipe; + } + + + /** + * The method takes in an IngredientsAtHand object and writes it to a .register-file with the + * provided String as title. The file contains no other information than a simple list of FoodItem + * constants separated by new-line. The resulting file is stored at /main/recourses/recipes/. An + * IllegalArgumentException is thrown if the ingredients at hand object is null. IOExceptions may + * occur upon writing to file, in which case the stacktrace is printed to terminal. + * + * @param ingredientsAtHand An IngredientsAtHand object that holds a collection of constants of + * the FoodItem enum class. + * @param fileDestination The path and title by which to name the file that the ingredients at + * hand are written to. + * @throws IOException if an input or output error occurs. + */ + public static void writeIngredientsAtHand(IngredientsAtHand ingredientsAtHand, + String fileDestination) throws IOException { + StringBuilder sb = new StringBuilder(); + System.out.println("Write IAH: " + fileDestination + fileType); + + try (FileWriter fileWriter = new FileWriter(fileDestination + fileType)) { + if (ingredientsAtHand == null) { + fileWriter.write(""); + } else { + ingredientsAtHand.getIngredientsAtHand() + .forEach((ingredient) -> sb.append(ingredient).append("\n")); + try { + fileWriter.write(String.valueOf(sb)); + } catch (IOException e) { + throw new RuntimeException(e); } + } + } + } + + /** + * The method reads an IngredientsAtHand object from the .register file with the name provided as + * a parameter and stored at /main/recourses/recipes/. If the file is not found, a + * FileNotFoundException is thrown and null is returned instead of a IngredientsAtHand object. + * + * @param fileDestination Path and title of the file to read the IngredientsAtHand object from. + * @return An IngredientsAtHand object based on the provided .register file. + */ + public static IngredientsAtHand readIngredientsAtHand(String fileDestination) throws IOException { + File file = new File(fileDestination + fileType); + IngredientsAtHand ingredientsAtHand = new IngredientsAtHand(); + + if (!file.exists()) { + file.createNewFile(); } - /** - * The method reads an IngredientsAtHand object from the .register file with the name provided as a parameter - * and stored at /main/recourses/recipes/. If the file is not found, a FileNotFoundException is thrown and - * null is returned instead of a IngredientsAtHand object. - * @param fileDestination Path and title of the file to read the IngredientsAtHand object from. - * @return An IngredientsAtHand object based on the provided .register file. - */ - public static IngredientsAtHand readIngredientsAtHand(String fileDestination) throws IOException { - File file = new File(fileDestination + fileType); - IngredientsAtHand ingredientsAtHand = new IngredientsAtHand(); - - if (!file.exists()){ - file.createNewFile(); - } - - try (Scanner sc = new Scanner(file)) { - String line; + try (Scanner sc = new Scanner(file)) { + String line; - while (sc.hasNext()) { - line = sc.next(); - if (!line.isBlank()) { - ingredientsAtHand.addIngredient(FoodItem.valueOf(line)); - } - } - } catch (FileNotFoundException e) { - return null; + while (sc.hasNext()) { + line = sc.next(); + if (!line.isBlank()) { + ingredientsAtHand.addIngredient(FoodItem.valueOf(line)); } - return ingredientsAtHand; + } + } catch (FileNotFoundException e) { + return null; } + return ingredientsAtHand; + } } \ No newline at end of file diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FoodItem.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FoodItem.java index 94c1696f841b361237b67e790347d9448b8857e3..74c431c2ff0b64961c97ba1a159b27ff17c4d4b8 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FoodItem.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FoodItem.java @@ -1,344 +1,345 @@ package no.ntnu.idatt1002.demo.data.recipes; /** - * The FoodItem enum class defines a set of food types that may be serving as ingredients in recipes and that the - * user may, or may not, have available in the cupboard, fridge or freezer. The label is a strict lower case - * version of the constant value where the underscore is replaced by a space. This value is used at the front-end - * to represent each enum value. + * The FoodItem enum class defines a set of food types that may be serving as ingredients in recipes + * and that the user may, or may not, have available in the cupboard, fridge or freezer. The label + * is a strict lower case version of the constant value where the underscore is replaced by a space. + * This value is used at the front-end to represent each enum value. * * @author hannesofie * @since 13.03.2023 */ public enum FoodItem { - /** - * Onion - */ - ONION("onion"), - - /** - * Minced meat. - */ - MINCED_MEAT("minced meat"), - - /** - * Potato. - */ - POTATO("potato"), - - /** - * Yellow cheese. - */ - YELLOW_CHEESE("yellow cheese"), - - /** - * Wheat flour. - */ - WHEAT_FLOUR("wheat flour"), - - /** - * Milk. - */ - MILK("milk"), - - /** - * Tomato. - */ - TOMATO("tomato"), - - /** - * Orange. - */ - ORANGE("orange"), - - /** - * Lemon. - */ - LEMON("lemon"), - - /** - * Salsa sauce. - */ - SALSA_SAUCE("salsa sauce"), - - /** - * Cucumber. - */ - CUCUMBER("cucumber"), - - /** - * Salad. - */ - SALAD("salad"), - - /** - * Spinach. - */ - SPINACH("spinach"), - - /** - * Spring roll. - */ - SPRING_ROLL("spring roll"), - - /** - * Bell pepper. - */ - BELL_PEPPER("bell pepper"), - - /** - * Chickpeas. - */ - CHICKPEAS("chickpeas"), - - /** - * Spaghetti. - */ - SPAGHETTI("spaghetti"), - - /** - * Pasta. - */ - PASTA("pasta"), - - /** - * Cream. - */ - CREAM("cream"), - - /** - * Honey. - */ - HONEY("honey"), - - /** - * Vinegar. - */ - VINEGAR("vinegar"), - - /** - * Tomato paste. - */ - TOMATO_PASTE("tomato paste"), - - /** - * Chili. - */ - CHILLI("chilli"), - - /** - * Egg. - */ - EGG("egg"), - - /** - * Olive oil. - */ - OLIVE_OIL("olive oil"), - - /** - * Ham. - */ - HAM("ham"), - - /** - * Parmesan. - */ - PARMESAN("parmesan"), - - /** - * Snap pea. - */ - SNAP_PEA("snap pea"), - - /** - * Macaroni. - */ - MACARONI("macaroni"), - - /** - * Salmon. - */ - SALMON("salmon"), - - /** - * Fish. - */ - FISH("fish"), - - /** - * Carrot. - */ - CARROT("carrot"), - - /** - * Butter. - */ - BUTTER("butter"), - - /** - * Leek. - */ - LEEK("leek"), - - /** - * Bread crumbs. - */ - BREADCRUMBS("breadcrumbs"), - - /** - * Oil. - */ - OIL("oil"), - - /** - * Summer cutlet. - */ - SUMMER_CUTLET("summer cutlet"), - - /** - * Red onion. - */ - RED_ONION("red onion"), - - /** - * Avocado. - */ - AVOCADO("avocado"), - - /** - * Lemon juice. - */ - LEMON_JUICE("lemon juice"), - - /** - * Dry thyme. - */ - DRY_THYME("dry thyme"), - - /** - * Fresh yeast. - */ - FRESH_YEAST("fresh yeast"), - - /** - * Garlic clove. - */ - GARLIC_CLOVE("garlic clove"), - - /** - * Ginger. - */ - GINGER("ginger"), - - /** - * Canned tomato. - */ - CANNED_TOMATO("canned tomato"), - - /** - * Dry basil. - */ - DRY_BASIL("dry basil"), - - /** - * Fresh basil. - */ - FRESH_BASIL("fresh basil"), - - /** - * Celery. - */ - CELERY("celery"), - - /** - * Broth. - */ - BROTH("broth"), - - /** - * Bay leaf. - */ - BAY_LEAF("bay leaf"), - - /** - * Chili beans. - */ - CHILLI_BEANS("chilli beans"), - - /** - * Chili powder. - */ - CHILLI_POWDER("chilli powder"), - - /** - * Cumin powder. - */ - CUMIN_POWDER("cumin powder"), - - /** - * Pie dough. - */ - PIE_DOUGH("pie dough"), - - /** - * Broccoli. - */ - BROCCOLI("broccoli"), - - /** - * Lam - */ - LAM("lam"), - - /** - * Sugar. - */ - SUGAR("sugar"), - - /** - * Shallot. - */ - SHALLOT("shallot"), - - /** - * Red wine. - */ - RED_WINE("red wine"), - - /** - * White bananas. - */ - WHITE_BEANS("white beans"), - - /** - * Frozen green peas - */ - FROZEN_GREEN_PEAS("frozen green peas"), - - /** - * Sausage. - */ - SAUSAGE("sausage"), - - /** - * Dry oregano - */ - DRY_OREGANO("dry oregano"); - - /** - * Label of the categories. The label formats - * the string value of the categories two string in lower caps. - */ - public final String label; - - /** - * The constructor of the enum constants takes in a string label and - * assigns it to its respective constant. - * The label is used for representation in texts and lists at the frontend of the application. - * @param label A lower-case and readable string representation of the enum constant. - */ - FoodItem(String label) { - this.label = label; - } + /** + * Onion. + */ + ONION("onion"), + + /** + * Minced meat. + */ + MINCED_MEAT("minced meat"), + + /** + * Potato. + */ + POTATO("potato"), + + /** + * Yellow cheese. + */ + YELLOW_CHEESE("yellow cheese"), + + /** + * Wheat flour. + */ + WHEAT_FLOUR("wheat flour"), + + /** + * Milk. + */ + MILK("milk"), + + /** + * Tomato. + */ + TOMATO("tomato"), + + /** + * Orange. + */ + ORANGE("orange"), + + /** + * Lemon. + */ + LEMON("lemon"), + + /** + * Salsa sauce. + */ + SALSA_SAUCE("salsa sauce"), + + /** + * Cucumber. + */ + CUCUMBER("cucumber"), + + /** + * Salad. + */ + SALAD("salad"), + + /** + * Spinach. + */ + SPINACH("spinach"), + + /** + * Spring roll. + */ + SPRING_ROLL("spring roll"), + + /** + * Bell pepper. + */ + BELL_PEPPER("bell pepper"), + + /** + * Chickpeas. + */ + CHICKPEAS("chickpeas"), + + /** + * Spaghetti. + */ + SPAGHETTI("spaghetti"), + + /** + * Pasta. + */ + PASTA("pasta"), + + /** + * Cream. + */ + CREAM("cream"), + + /** + * Honey. + */ + HONEY("honey"), + + /** + * Vinegar. + */ + VINEGAR("vinegar"), + + /** + * Tomato paste. + */ + TOMATO_PASTE("tomato paste"), + + /** + * Chili. + */ + CHILLI("chilli"), + + /** + * Egg. + */ + EGG("egg"), + + /** + * Olive oil. + */ + OLIVE_OIL("olive oil"), + + /** + * Ham. + */ + HAM("ham"), + + /** + * Parmesan. + */ + PARMESAN("parmesan"), + + /** + * Snap pea. + */ + SNAP_PEA("snap pea"), + + /** + * Macaroni. + */ + MACARONI("macaroni"), + + /** + * Salmon. + */ + SALMON("salmon"), + + /** + * Fish. + */ + FISH("fish"), + + /** + * Carrot. + */ + CARROT("carrot"), + + /** + * Butter. + */ + BUTTER("butter"), + + /** + * Leek. + */ + LEEK("leek"), + + /** + * Bread crumbs. + */ + BREADCRUMBS("breadcrumbs"), + + /** + * Oil. + */ + OIL("oil"), + + /** + * Summer cutlet. + */ + SUMMER_CUTLET("summer cutlet"), + + /** + * Red onion. + */ + RED_ONION("red onion"), + + /** + * Avocado. + */ + AVOCADO("avocado"), + + /** + * Lemon juice. + */ + LEMON_JUICE("lemon juice"), + + /** + * Dry thyme. + */ + DRY_THYME("dry thyme"), + + /** + * Fresh yeast. + */ + FRESH_YEAST("fresh yeast"), + + /** + * Garlic clove. + */ + GARLIC_CLOVE("garlic clove"), + + /** + * Ginger. + */ + GINGER("ginger"), + + /** + * Canned tomato. + */ + CANNED_TOMATO("canned tomato"), + + /** + * Dry basil. + */ + DRY_BASIL("dry basil"), + + /** + * Fresh basil. + */ + FRESH_BASIL("fresh basil"), + + /** + * Celery. + */ + CELERY("celery"), + + /** + * Broth. + */ + BROTH("broth"), + + /** + * Bay leaf. + */ + BAY_LEAF("bay leaf"), + + /** + * Chili beans. + */ + CHILLI_BEANS("chilli beans"), + + /** + * Chili powder. + */ + CHILLI_POWDER("chilli powder"), + + /** + * Cumin powder. + */ + CUMIN_POWDER("cumin powder"), + + /** + * Pie dough. + */ + PIE_DOUGH("pie dough"), + + /** + * Broccoli. + */ + BROCCOLI("broccoli"), + + /** + * Lam. + */ + LAM("lam"), + + /** + * Sugar. + */ + SUGAR("sugar"), + + /** + * Shallot. + */ + SHALLOT("shallot"), + + /** + * Red wine. + */ + RED_WINE("red wine"), + + /** + * White bananas. + */ + WHITE_BEANS("white beans"), + + /** + * Frozen green peas. + */ + FROZEN_GREEN_PEAS("frozen green peas"), + + /** + * Sausage. + */ + SAUSAGE("sausage"), + + /** + * Dry oregano. + */ + DRY_OREGANO("dry oregano"); + + /** + * Label of the categories. The label formats the string value of the categories two string in + * lower caps. + */ + public final String label; + + /** + * The constructor of the enum constants takes in a string label and assigns it to its respective + * constant. The label is used for representation in texts and lists at the frontend of the + * application. + * + * @param label A lower-case and readable string representation of the enum constant. + */ + FoodItem(String label) { + this.label = label; + } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Ingredient.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Ingredient.java index 76a5b9e78d1f1f5d105d6b928821c3fc373606f3..cd00ad1bac87c8a71f49793678a27fd060335da4 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Ingredient.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Ingredient.java @@ -1,123 +1,142 @@ package no.ntnu.idatt1002.demo.data.recipes; /** - * The Ingredient class represents an ingredient that can be part of a recipe in real life and/or - * be available to the user in real life. When the ingredient is part of a recipe, the subclass called - * RecipeIngredient is used. An ingredient belongs to a food type among the values of the FoodItem enum class. - * Examples are onion, tomato, spaghetti, chicken etc. The ingredient is provided in a specific amount and unit - * of measure. + * The Ingredient class represents an ingredient that can be part of a recipe in real life and/or be + * available to the user in real life. When the ingredient is part of a recipe, the subclass called + * RecipeIngredient is used. An ingredient belongs to a food type among the values of the FoodItem + * enum class. Examples are onion, tomato, spaghetti, chicken etc. The ingredient is provided in a + * specific amount and unit of measure. * * @author hannesofie */ public class Ingredient { - private FoodItem foodType; - private double amount; - private MeasuringUnit unit; + private FoodItem foodType; + private double amount; + private MeasuringUnit unit; - /** - * The constructor of a new Ingredient object takes in three mandatory fields; ingredient type as defined in - * the enum class FoodItem, an amount and a unit of measure defined in the enum class MeasuringUnit. The amount - * must be a positive number. - * @param ingredient What type of food the ingredient is. - * @param amount The amount of the ingredient. - * @param unit The unit of measure of the given amount of the ingredient. - */ - public Ingredient(FoodItem ingredient, double amount, MeasuringUnit unit) { - if(ingredient == null | amount <= 0.0f | unit == null) { - throw new IllegalArgumentException("The ingredient must have a type, amount and measuring unit."); - } - this.foodType = ingredient; - this.amount = amount; - this.unit = unit; + /** + * The constructor of a new Ingredient object takes in three mandatory fields; ingredient type as + * defined in the enum class FoodItem, an amount and a unit of measure defined in the enum class + * MeasuringUnit. The amount must be a positive number. + * + * @param ingredient What type of food the ingredient is. + * @param amount The amount of the ingredient. + * @param unit The unit of measure of the given amount of the ingredient. + */ + public Ingredient(FoodItem ingredient, double amount, MeasuringUnit unit) { + if (ingredient == null | amount <= 0.0f | unit == null) { + throw new IllegalArgumentException( + "The ingredient must have a type, amount and measuring unit."); } + this.foodType = ingredient; + this.amount = amount; + this.unit = unit; + } - /** - * The method returns the food type that the ingredient belongs to among the valid types in the FoodItem enum class. - * @return What type of food the ingredient is. - */ - public FoodItem getFoodType() { - return foodType; - } + /** + * The method returns the food type that the ingredient belongs to among the valid types in the + * FoodItem enum class. + * + * @return What type of food the ingredient is. + */ + public FoodItem getFoodType() { + return foodType; + } - /** - * The method takes in a value of the FoodItem enum and sets the ingredient's foodType field equal to this constant. - * If null is given an IllegalArgumentException is thrown. - * - * @param foodType The type of food to assign the ingredient to. - */ - public void setFoodType(FoodItem foodType) { - if(foodType == null) { - throw new IllegalArgumentException("The food type must be set to a valid value of FoodItem."); - } - this.foodType = foodType; + /** + * The method takes in a value of the FoodItem enum and sets the ingredient's foodType field equal + * to this constant. If null is given an IllegalArgumentException is thrown. + * + * @param foodType The type of food to assign the ingredient to. + */ + public void setFoodType(FoodItem foodType) { + if (foodType == null) { + throw new IllegalArgumentException("The food type must be set to a valid value of FoodItem."); } + this.foodType = foodType; + } - /** - * The method returns the amount of an ingredient as the datatype double. - * @return The amount of an ingredient as double. - */ - public double getAmount() { - return amount; - } + /** + * The method returns the amount of an ingredient as the datatype double. + * + * @return The amount of an ingredient as double. + */ + public double getAmount() { + return amount; + } - /** - * The method takes in a new amount as a double and sets the ingredient's amount field equal to this value. - * If the provided value is not a positive double, an IllegalArgumentException is thrown. - * @param amount The amount of an ingredient as double. - */ - public void setAmount(double amount) { - if(amount <= 0.0f) { - throw new IllegalArgumentException("The amount of an ingredient cannot be zero or negative."); - } - this.amount = amount; + /** + * The method takes in a new amount as a double and sets the ingredient's amount field equal to + * this value. If the provided value is not a positive double, an IllegalArgumentException is + * thrown. + * + * @param amount The amount of an ingredient as double. + */ + public void setAmount(double amount) { + if (amount <= 0.0f) { + throw new IllegalArgumentException("The amount of an ingredient cannot be zero or negative."); } + this.amount = amount; + } - /** - * The method returns the unit of measure of the ingredient as a value of the MeasuringUnit enum class. - * @return The unit of measure of the given amount of the ingredient. - */ - public MeasuringUnit getUnit() { - return unit; - } + /** + * The method returns the unit of measure of the ingredient as a value of the MeasuringUnit enum + * class. + * + * @return The unit of measure of the given amount of the ingredient. + */ + public MeasuringUnit getUnit() { + return unit; + } - /** - * The method takes in a value of the MeasuringUnit enum class and sets the ingredient's unit equal to this - * value. - * @param unit The unit of measure of the given amount of the ingredient. - */ - public void setUnit(MeasuringUnit unit) { - if(unit == null) { - throw new IllegalArgumentException("The food's measuring unit must be set to a valid value of MeasuringUnit."); - } - this.unit = unit; + /** + * The method takes in a value of the MeasuringUnit enum class and sets the ingredient's unit + * equal to this value. + * + * @param unit The unit of measure of the given amount of the ingredient. + */ + public void setUnit(MeasuringUnit unit) { + if (unit == null) { + throw new IllegalArgumentException( + "The food's measuring unit must be set to a valid value of MeasuringUnit."); } + this.unit = unit; + } - /** - * The method returns a String representation of an Ingredient object, listing its type, amount and unit. - * @return A String representation of the ingredient object. - */ - @Override - public String toString() { - return "Ingredient{" + - "foodType=" + foodType.label + - ", amount=" + amount + - ", unit=" + unit.label + - '}'; - } + /** + * The method returns a String representation of an Ingredient object, listing its type, amount + * and unit. + * + * @return A String representation of the ingredient object. + */ + @Override + public String toString() { + return "Ingredient{" + + "foodType=" + foodType.label + + ", amount=" + amount + + ", unit=" + unit.label + + '}'; + } - /** - * The method checks if a given object is equal to the ingredient object. - * If the object is of the same class as well as having the same value for each class field, - * the object is equal to the Ingredient. - * @param o An Object to which the Ingredient should be compared. - * @return True if the object is equivalent to the Ingredient, false otherwise. - */ - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Ingredient that)) return false; - return Double.compare(that.amount, amount) == 0 && foodType == that.foodType && unit == that.unit; + /** + * The method checks if a given object is equal to the ingredient object. If the object is of the + * same class as well as having the same value for each class field, the object is equal to the + * Ingredient. + * + * @param o An Object to which the Ingredient should be compared. + * @return True if the object is equivalent to the Ingredient, false otherwise. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Ingredient that)) { + return false; } + return Double.compare(that.amount, amount) == 0 && foodType == that.foodType + && unit == that.unit; + } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/IngredientsAtHand.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/IngredientsAtHand.java index 5c4d029f3efab2cd34521180d92223024dcbe022..78e2b97efef72a71e4e279eaf42e3e538356bdab 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/IngredientsAtHand.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/IngredientsAtHand.java @@ -4,55 +4,62 @@ import java.util.ArrayList; import java.util.List; /** - * The class holds a collection of FoodItem constants in an ArrayList that represents the groceries that the - * user has available in real life. The class provides methods to add and remove food types from the collection - * as well as checking if a given food type is available, i.e. is part of the collection. + * The class holds a collection of FoodItem constants in an ArrayList that represents the groceries + * that the user has available in real life. The class provides methods to add and remove food types + * from the collection as well as checking if a given food type is available, i.e. is part of the + * collection. * * @author hannesofie */ public class IngredientsAtHand { - private final ArrayList<FoodItem> ingredientsAtHand = new ArrayList<>(); + private final ArrayList<FoodItem> ingredientsAtHand = new ArrayList<>(); - /** - * The method returns the collection of ingredients at hand as an arraylist of FoodItem enum constants. - * @return The collection of food types at hand to the user. - */ - public List<FoodItem> getIngredientsAtHand() { - return ingredientsAtHand; - } + /** + * The method returns the collection of ingredients at hand as an arraylist of FoodItem enum + * constants. + * + * @return The collection of food types at hand to the user. + */ + public List<FoodItem> getIngredientsAtHand() { + return ingredientsAtHand; + } - /** - * The method takes in an ingredient object and adds it to the collection of ingredients at hand. - * @param ingredient The food type to add to the collection of ingredients at hand. - */ - public void addIngredient(FoodItem ingredient) { - if(!this.atHand(ingredient) && ingredient != null) { - this.ingredientsAtHand.add(ingredient); - } + /** + * The method takes in an ingredient object and adds it to the collection of ingredients at hand. + * + * @param ingredient The food type to add to the collection of ingredients at hand. + */ + public void addIngredient(FoodItem ingredient) { + if (!this.atHand(ingredient) && ingredient != null) { + this.ingredientsAtHand.add(ingredient); } + } - /** - * The method takes in a constant of the FoodType enum class and checks if it is present in the collection. - * If it is present, true is returned, otherwise false. - * @param foodItem A constant value of the FoodItem enum class to check for in the collection - * of ingredients at hand. - * @return True if the food type is at hand, otherwise false. - */ - public boolean atHand(FoodItem foodItem) { - return ingredientsAtHand.stream().anyMatch( (in) -> in.equals(foodItem)); - } + /** + * The method takes in a constant of the FoodType enum class and checks if it is present in the + * collection. If it is present, true is returned, otherwise false. + * + * @param foodItem A constant value of the FoodItem enum class to check for in the collection of + * ingredients at hand. + * @return True if the food type is at hand, otherwise false. + */ + public boolean atHand(FoodItem foodItem) { + return ingredientsAtHand.stream().anyMatch((in) -> in.equals(foodItem)); + } - /** - * The method takes in a value of the FoodItem enum as a parameter and removes it from the collection of - * ingredients at hand if it exists and returns true. If no ingredient of the given type was found in the - * collection, false is returned. - * @param ingredientType What type of food to remove from the list of ingredients at hand. - * @return True if the ingredient was found among the ingredients at hand and removed, false otherwise. - */ - public boolean removeIngredient(FoodItem ingredientType) { - return ingredientsAtHand.remove(ingredientType); - } + /** + * The method takes in a value of the FoodItem enum as a parameter and removes it from the + * collection of ingredients at hand if it exists and returns true. If no ingredient of the given + * type was found in the collection, false is returned. + * + * @param ingredientType What type of food to remove from the list of ingredients at hand. + * @return True if the ingredient was found among the ingredients at hand and removed, false + * otherwise. + */ + public boolean removeIngredient(FoodItem ingredientType) { + return ingredientsAtHand.remove(ingredientType); + } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/MeasuringUnit.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/MeasuringUnit.java index d1d53182bbc63cc7a09537e73894a313c6b07336..e9216422f6194dab37bb966247dbc4c092fd29cc 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/MeasuringUnit.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/MeasuringUnit.java @@ -1,9 +1,9 @@ package no.ntnu.idatt1002.demo.data.recipes; /** - * The enum class defines a set of valid units of measurements related to the ingredients and recipes. - * The label property of each constant provides a lower-case representation of each unit that can be used in - * presentation to the user. + * The enum class defines a set of valid units of measurements related to the ingredients and + * recipes. The label property of each constant provides a lower-case representation of each unit + * that can be used in presentation to the user. * * @author hannesofie * @since 13.03.2023 @@ -11,73 +11,74 @@ package no.ntnu.idatt1002.demo.data.recipes; public enum MeasuringUnit { - /** - * Deciliter. - */ - DL("dl."), + /** + * Deciliter. + */ + DL("dl."), - /** - * Liter. - */ - L("l."), + /** + * Liter. + */ + L("l."), - /** - * Teaspoon. - */ - TSP("tsp."), + /** + * Teaspoon. + */ + TSP("tsp."), - /** - * Tablespoon. - */ - TBS("tbs."), + /** + * Tablespoon. + */ + TBS("tbs."), - /** - * Gram. - */ - GR("gr."), + /** + * Gram. + */ + GR("gr."), - /** - * Kilogram - */ - KG("kg."), + /** + * Kilogram. + */ + KG("kg."), - /** - * Pieces. - */ - PC("pieces"), + /** + * Pieces. + */ + PC("pieces"), - /** - * Can. - */ - CAN("can"), + /** + * Can. + */ + CAN("can"), - /** - * Slice - */ - SLICE("slice"), + /** + * Slice. + */ + SLICE("slice"), - /** - * Pack - */ - PKG("pack"), + /** + * Pack. + */ + PKG("pack"), - /** - * Cubes. - */ - CB("cubes"); + /** + * Cubes. + */ + CB("cubes"); - /** - * Label of the categories. The label formats - * the string value of the categories two string in lower caps. - */ - public final String label; + /** + * Label of the categories. The label formats the string value of the categories two string in + * lower caps. + */ + public final String label; - /** - * The constructor of each enum constant takes in a string representation of the constant that is more suited for - * presentation at the frontend. - * @param label Lower case representation of the unit of measure. - */ - MeasuringUnit(String label) { - this.label = label; - } + /** + * The constructor of each enum constant takes in a string representation of the constant that is + * more suited for presentation at the frontend. + * + * @param label Lower case representation of the unit of measure. + */ + MeasuringUnit(String label) { + this.label = label; + } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Recipe.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Recipe.java index 528fd5a93711d958ce0bef0614c261404052aa78..c88829efa4b79e2cccd670bd202318bdc200794b 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Recipe.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/Recipe.java @@ -5,215 +5,243 @@ import java.util.List; import java.util.Objects; /** - * The recipe class represents a dinner recipe for the user. It has a name, a textual instruction and - * holds a collection of recipe ingredient items. Each recipe ingredient has a food type, amount, unit of measure and - * a status(true/false) of whether it is at hand or not. - * Apart for methods to get and alter fields, the class provides the following specialized methods: - * - updateIngredientStatus: takes in a list of food types at hand and updates the 'atHand' property of each - * of its ingredients accordingly. - * - getMissingIngredients: returns the number of ingredients in the recipe that are not at hand. - * - getMissingList: returns an ArrayList of the FoodItem labels (String) that are not at hand. - * specific food type - * When the Recipe has not been compared to a collection of ingredients at hand, the number of missing - * ingredients is set to 0 and the list of missing ingredients is set to an empty ArrayList. + * The recipe class represents a dinner recipe for the user. It has a name, a textual instruction + * and holds a collection of recipe ingredient items. Each recipe ingredient has a food type, + * amount, unit of measure and a status(true/false) of whether it is at hand or not. Apart for + * methods to get and alter fields, the class provides the following specialized methods: - + * updateIngredientStatus: takes in a list of food types at hand and updates the 'atHand' property + * of each of its ingredients accordingly. - getMissingIngredients: returns the number of + * ingredients in the recipe that are not at hand. - getMissingList: returns an ArrayList of the + * FoodItem labels (String) that are not at hand. specific food type When the Recipe has not been + * compared to a collection of ingredients at hand, the number of missing ingredients is set to 0 + * and the list of missing ingredients is set to an empty ArrayList. * * @author hannesofie */ public class Recipe { - private String name; - private final ArrayList<RecipeIngredient> ingredientList = new ArrayList<>(); - private String instructions; - - private int missingIngredients = 0; - private ArrayList<String> missingList = new ArrayList<>(); - - /** - * The constructor method creates a new Recipe object by setting the name and instructions as Strings. - * @param name Name of the recipe. - * @param instructions The instructions of the recipe. - */ - public Recipe(String name, String instructions ) { - if(name.isBlank() | instructions.isBlank()) { - throw new IllegalArgumentException("The recipe must have a name and a description."); - } - this.name = name; - this.instructions = instructions; + private String name; + private final ArrayList<RecipeIngredient> ingredientList = new ArrayList<>(); + private String instructions; + + private int missingIngredients = 0; + private ArrayList<String> missingList = new ArrayList<>(); + + /** + * The constructor method creates a new Recipe object by setting the name and instructions as + * Strings. + * + * @param name Name of the recipe. + * @param instructions The instructions of the recipe. + */ + public Recipe(String name, String instructions) { + if (name.isBlank() | instructions.isBlank()) { + throw new IllegalArgumentException("The recipe must have a name and a description."); } - - /** - * The method returns the name of the recipe. - * @return The name of the recipe as a String. - */ - public String getName() { - return name; + this.name = name; + this.instructions = instructions; + } + + /** + * The method returns the name of the recipe. + * + * @return The name of the recipe as a String. + */ + public String getName() { + return name; + } + + /** + * The method takes in a String to which the name of the recipe is set. If a blank String is + * given, an IllegalArgumentException is thrown. + * + * @param name New name for the recipe. + */ + public void setName(String name) { + if (name.isBlank()) { + throw new IllegalArgumentException("The recipe name cannot be left blank."); } - - /** - * The method takes in a String to which the name of the recipe is set. If a blank String is given, an - * IllegalArgumentException is thrown. - * @param name New name for the recipe. - */ - public void setName(String name) { - if(name.isBlank()) { - throw new IllegalArgumentException("The recipe name cannot be left blank."); - } - this.name = name; + this.name = name; + } + + /** + * The method returns the list of RecipeIngredients that the recipe consists of. + * + * @return A list of RecipeIngredients belonging to the recipe. + */ + public List<RecipeIngredient> getIngredientList() { + return ingredientList; + } + + /** + * The method returns the instructions of the recipe. + * + * @return The instructions of the recipe as a String. + */ + public String getInstructions() { + return instructions; + } + + /** + * The method takes a String as a parameter to which the recipe instructions are set, provided + * that the String is not blank, in which case an IllegalArgumentException is thrown instead. + * + * @param instructions The new instructions of the recipe as a String. + */ + public void setInstructions(String instructions) { + if (instructions.isBlank()) { + throw new IllegalArgumentException("The recipe instructions cannot be left blank."); } - - /** - * The method returns the list of RecipeIngredients that the recipe consists of. - * @return A list of RecipeIngredients belonging to the recipe. - */ - public List<RecipeIngredient> getIngredientList() { - return ingredientList; - } - - /** - * The method returns the instructions of the recipe. - * @return The instructions of the recipe as a String. - */ - public String getInstructions() { - return instructions; + this.instructions = instructions; + } + + /** + * The method takes in a constant of the FoodItem enum class and searches for it among the + * recipe's ingredients. If it is found, the recipe ingredient object is returned, if it is not + * found, null is returned. + * + * @param ingredientType A constant value defined by the FoodItem enum class. + * @return The recipe ingredient if it is present in the recipe ingredient list, null otherwise. + */ + public RecipeIngredient getIngredient(FoodItem ingredientType) { + if (ingredientType == null) { + return null; } - - /** - * The method takes a String as a parameter to which the recipe instructions are set, provided that the String - * is not blank, in which case an IllegalArgumentException is thrown instead. - * @param instructions The new instructions of the recipe as a String. - */ - public void setInstructions(String instructions) { - if(instructions.isBlank()) { - throw new IllegalArgumentException("The recipe instructions cannot be left blank."); - } - this.instructions = instructions; - } - - /** - * The method takes in a constant of the FoodItem enum class and searches for it among the recipe's ingredients. - * If it is found, the recipe ingredient object is returned, if it is not found, null is returned. - * @param ingredientType A constant value defined by the FoodItem enum class. - * @return The recipe ingredient if it is present in the recipe ingredient list, null otherwise. - */ - public RecipeIngredient getIngredient(FoodItem ingredientType) { - if(ingredientType == null) return null; - return this.getIngredientList().stream() - .filter((ingredient) -> ingredient.getFoodType() == ingredientType) - .findFirst().orElse(null); - } - - /** - * The method adds an ingredient to the recipe if it is not already in the recipe, in which case the existing - * ingredient of the same food type is updated with the parameters provided to this method. The parameters are - * a constant of the FoodItem enum class to provide the food type, a double value representing the amount of - * the ingredient and the measuring unit given as a constant of the MeasuringUnit enum class. If the - * ingredient is neither added nor updated successfully, false is returned, otherwise true is returned. - * @param ingredientType The type of food the ingredient belongs to. - * @param amount The amount of the ingredient when part of this recipe. - * @param unit The measuring unit of the ingredient part of this recipe. - * @return True if the ingredient is successfully added or altered, otherwise false. - */ - public boolean addIngredient(FoodItem ingredientType, double amount, MeasuringUnit unit) { - if(ingredientList.stream().anyMatch((ingredient) -> ingredient.getFoodType() == ingredientType)) { - try { - getIngredient(ingredientType).setAmount(amount); - getIngredient(ingredientType).setUnit(unit); - - } catch (IllegalArgumentException e) { - return false; - } - } else { - try { - this.ingredientList.add(new RecipeIngredient(ingredientType, amount, unit)); - } catch (IllegalArgumentException e) { - return false; - } - } - return true; + return this.getIngredientList().stream() + .filter((ingredient) -> ingredient.getFoodType() == ingredientType) + .findFirst().orElse(null); + } + + /** + * The method adds an ingredient to the recipe if it is not already in the recipe, in which case + * the existing ingredient of the same food type is updated with the parameters provided to this + * method. The parameters are a constant of the FoodItem enum class to provide the food type, a + * double value representing the amount of the ingredient and the measuring unit given as a + * constant of the MeasuringUnit enum class. If the ingredient is neither added nor updated + * successfully, false is returned, otherwise true is returned. + * + * @param ingredientType The type of food the ingredient belongs to. + * @param amount The amount of the ingredient when part of this recipe. + * @param unit The measuring unit of the ingredient part of this recipe. + * @return True if the ingredient is successfully added or altered, otherwise false. + */ + public boolean addIngredient(FoodItem ingredientType, double amount, MeasuringUnit unit) { + if (ingredientList.stream() + .anyMatch((ingredient) -> ingredient.getFoodType() == ingredientType)) { + try { + getIngredient(ingredientType).setAmount(amount); + getIngredient(ingredientType).setUnit(unit); + + } catch (IllegalArgumentException e) { + return false; + } + } else { + try { + this.ingredientList.add(new RecipeIngredient(ingredientType, amount, unit)); + } catch (IllegalArgumentException e) { + return false; + } } - - /** - * The method takes in an object of the IngredientsAtHand class which defines which foods the user has at hand. - * If the IngredientsAtHand object is null, and IllegalArgumentException is thrown. Otherwise, the recipe's - * ingredient list is iterated through, and the 'atHand' property of each ingredient is updated to true if - * it is present in the ingredients at hand collection, or false if it is not. - * In addition, the recipe's parameters "missingIngredients" and "missingList" are updated with the final - * number of ingredients in the recipe that are not at hand and the name of those recipes as Strings in an - * ArrayList, respectively. - * @param ingredientsAtHand An IngredientsAtHand object holding a collection of the food types that the - * user has available. - */ - public void updateIngredientStatus(IngredientsAtHand ingredientsAtHand) { - if (ingredientsAtHand == null) { - throw new NullPointerException("The ingredients at hand object must exist"); - } else { - missingList = new ArrayList<>(); - missingIngredients = (int) ingredientList.stream().filter((inRecipe) -> !ingredientsAtHand.atHand(inRecipe.getFoodType())).count(); - - ingredientList.forEach((inRecipe) -> { - inRecipe.setAtHand(ingredientsAtHand.atHand(inRecipe.getFoodType())); - if(!ingredientsAtHand.atHand(inRecipe.getFoodType())) { - missingList.add(inRecipe.getFoodType().label); - } - }); + return true; + } + + /** + * The method takes in an object of the IngredientsAtHand class which defines which foods the user + * has at hand. If the IngredientsAtHand object is null, and IllegalArgumentException is thrown. + * Otherwise, the recipe's ingredient list is iterated through, and the 'atHand' property of each + * ingredient is updated to true if it is present in the ingredients at hand collection, or false + * if it is not. In addition, the recipe's parameters "missingIngredients" and "missingList" are + * updated with the final number of ingredients in the recipe that are not at hand and the name of + * those recipes as Strings in an ArrayList, respectively. + * + * @param ingredientsAtHand An IngredientsAtHand object holding a collection of the food types + * that the user has available. + */ + public void updateIngredientStatus(IngredientsAtHand ingredientsAtHand) { + if (ingredientsAtHand == null) { + throw new NullPointerException("The ingredients at hand object must exist"); + } else { + missingList = new ArrayList<>(); + missingIngredients = (int) ingredientList.stream() + .filter((inRecipe) -> !ingredientsAtHand.atHand(inRecipe.getFoodType())).count(); + + ingredientList.forEach((inRecipe) -> { + inRecipe.setAtHand(ingredientsAtHand.atHand(inRecipe.getFoodType())); + if (!ingredientsAtHand.atHand(inRecipe.getFoodType())) { + missingList.add(inRecipe.getFoodType().label); } + }); } - - - /** - * The method returns the property 'missingIngredients' of the recipe. This is the number of ingredients - * as an int, contained in teh recipe, that is not part of the collection of ingredients at hand last updated for. - * @return The number of ingredients in the recipe that are not currently at hand. - */ - public int getMissingIngredients() { - return missingIngredients; + } + + + /** + * The method returns the property 'missingIngredients' of the recipe. This is the number of + * ingredients as an int, contained in teh recipe, that is not part of the collection of + * ingredients at hand last updated for. + * + * @return The number of ingredients in the recipe that are not currently at hand. + */ + public int getMissingIngredients() { + return missingIngredients; + } + + /** + * The method returns an ArrayList of Strings representing each of the food types that the recipe + * is missing relative to the collection of ingredients at hand last updated for. + * + * @return The ingredients in this recipe that are not currently at hand as a list of Strings. + */ + public ArrayList<String> getMissingList() { + return missingList; + } + + /** + * The method returns a String representation of the recipe, listing its name, ingredients and + * instructions. + * + * @return A String representation of the recipe. + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append(this.name).append("\n"); + this.getIngredientList().forEach((ingredient) -> sb.append(ingredient).append("\n")); + sb.append(this.getInstructions()); + + return String.valueOf(sb); + } + + /** + * The method takes in another Object and checks whether it is equal to the current recipe object. + * It first checks if the object reference is the same, in which case true is returned. If not, it + * checks that the object is not null and whether its class is dissimilar, for which false is also + * returned. Finally, the object is cast as a Recipe and compared by name. If the two recipe's + * names are the same, they are considered the same. + * + * @param o A general Object. + * @return True if the object is equal to the current recipe, false otherwise. + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - /** - * The method returns an ArrayList of Strings representing each of the food types that the recipe is missing - * relative to the collection of ingredients at hand last updated for. - * @return The ingredients in this recipe that are not currently at hand as a list of Strings. - */ - public ArrayList<String> getMissingList() { - return missingList; - } - - /** - * The method returns a String representation of the recipe, listing its name, ingredients and instructions. - * @return A String representation of the recipe. - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - - sb.append(this.name).append("\n"); - this.getIngredientList().forEach((ingredient) -> sb.append(ingredient).append("\n")); - sb.append(this.getInstructions()); - - return String.valueOf(sb); - } - - /** - * The method takes in another Object and checks whether it is equal to the current recipe object. It first checks - * if the object reference is the same, in which case true is returned. If not, it checks that the object is not - * null and whether its class is dissimilar, for which false is also returned. Finally, the object is cast as a - * Recipe and compared by name. If the two recipe's names are the same, they are considered the same. - * @param o A general Object. - * @return True if the object is equal to the current recipe, false otherwise. - */ - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Recipe recipe)) return false; - return Objects.equals(name, recipe.name); - } - - /** - * The method returns a standard hash-code based on the recipe's name, ingredient list and instructions. - * @return A hash-code as an integer for the recipe. - */ - @Override - public int hashCode() { - return Objects.hash(name, ingredientList, instructions); + if (!(o instanceof Recipe recipe)) { + return false; } + return Objects.equals(name, recipe.name); + } + + /** + * The method returns a standard hash-code based on the recipe's name, ingredient list and + * instructions. + * + * @return A hash-code as an integer for the recipe. + */ + @Override + public int hashCode() { + return Objects.hash(name, ingredientList, instructions); + } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeIngredient.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeIngredient.java index 127586fb6f0ff5a3ef3856531f467c29f295dd47..93b3e74d1f28a10716c748ec2989738fc09708e0 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeIngredient.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeIngredient.java @@ -1,58 +1,62 @@ package no.ntnu.idatt1002.demo.data.recipes; /** - * The RecipeIngredient class is an extension of the Ingredient class used as part of recipes - * that also stored the boolean value 'atHand'. This value can be set to true whenever the given ingredient, - * being part of a recipe, is also at hand to the user. Ingredients that the user has available are stored in - * the IngredientsAtHand class. + * The RecipeIngredient class is an extension of the Ingredient class used as part of recipes that + * also stored the boolean value 'atHand'. This value can be set to true whenever the given + * ingredient, being part of a recipe, is also at hand to the user. Ingredients that the user has + * available are stored in the IngredientsAtHand class. * * @author hannesofie */ -public class RecipeIngredient extends Ingredient{ +public class RecipeIngredient extends Ingredient { - private boolean atHand = false; + private boolean atHand = false; - /** - * The constructor of a RecipeIngredient object inherits from the superclass Ingredient. The additional 'atHand' - * field is set to false ar default. - * @param ingredient What type of food the ingredient is. - * @param amount The amount of the ingredient. - * @param unit The unit of measure of the given amount of the ingredient. - */ - public RecipeIngredient(FoodItem ingredient, double amount, MeasuringUnit unit) { - super(ingredient, amount, unit); - } + /** + * The constructor of a RecipeIngredient object inherits from the superclass Ingredient. The + * additional 'atHand' field is set to false ar default. + * + * @param ingredient What type of food the ingredient is. + * @param amount The amount of the ingredient. + * @param unit The unit of measure of the given amount of the ingredient. + */ + public RecipeIngredient(FoodItem ingredient, double amount, MeasuringUnit unit) { + super(ingredient, amount, unit); + } - /** - * The method returns the boolean value of the atHand field for the ingredient. If the ingredient being part of - * a recipe is also contained in the collection of ingredients at hand to the user, true is returned, if not, - * false is returned. - * @return True of the current recipe ingredient is available to the user. - */ - public boolean isAtHand() { - return atHand; - } + /** + * The method returns the boolean value of the atHand field for the ingredient. If the ingredient + * being part of a recipe is also contained in the collection of ingredients at hand to the user, + * true is returned, if not, false is returned. + * + * @return True of the current recipe ingredient is available to the user. + */ + public boolean isAtHand() { + return atHand; + } - /** - * The method sets the value of the atHand field for the ingredient to either true or false. - * @param atHand A boolean value to set the 'atHand' status of the ingredient. - */ - public void setAtHand(boolean atHand) { - this.atHand = atHand; - } + /** + * The method sets the value of the atHand field for the ingredient to either true or false. + * + * @param atHand A boolean value to set the 'atHand' status of the ingredient. + */ + public void setAtHand(boolean atHand) { + this.atHand = atHand; + } - /** - * The method returns a String representation of a Recipe Ingredient object, listing its type, amount, unit - * and whether it is at hand or not. - * @return A String representation of the recipe ingredient object. - */ - @Override - public String toString() { - return "Ingredient{" + - "foodType=" + this.getFoodType().label + - ", amount=" + this.getAmount() + - ", unit=" + this.getUnit().label + - ", at hand=" + this.isAtHand() + - '}'; - } + /** + * The method returns a String representation of a Recipe Ingredient object, listing its type, + * amount, unit and whether it is at hand or not. + * + * @return A String representation of the recipe ingredient object. + */ + @Override + public String toString() { + return "Ingredient{" + + "foodType=" + this.getFoodType().label + + ", amount=" + this.getAmount() + + ", unit=" + this.getUnit().label + + ", at hand=" + this.isAtHand() + + '}'; + } } diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeRegister.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeRegister.java index 17ce164d66f90e15f9caf3c387bd73adffa2d4b4..e9bad4d9ff38fe08d86a9787f76d4c5a2df0bc08 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeRegister.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/RecipeRegister.java @@ -5,77 +5,84 @@ import java.util.Comparator; import java.util.stream.Collectors; /** - * The RecipeRegister class holds a collection of Recipes in a list and provides methods to access the recipes, - * add recipes to the register as well as to pick a number of recipe's best fitting a list of food types - * provided as a IngredientsAtHand object. The register is instantiated using the default constructor. + * The RecipeRegister class holds a collection of Recipes in a list and provides methods to access + * the recipes, add recipes to the register as well as to pick a number of recipe's best fitting a + * list of food types provided as a IngredientsAtHand object. The register is instantiated using the + * default constructor. * * @author hannesofie */ public class RecipeRegister { - private final ArrayList<Recipe> recipes = new ArrayList<>(); + private final ArrayList<Recipe> recipes = new ArrayList<>(); - /** - * The method returns the list of recipes in the Register. - * @return A list of recipes that belong to this register. - */ - public ArrayList<Recipe> getRecipes() { - return this.recipes; - } + /** + * The method returns the list of recipes in the Register. + * + * @return A list of recipes that belong to this register. + */ + public ArrayList<Recipe> getRecipes() { + return this.recipes; + } - /** - * The method takes in a Recipe object. If the recipe is already in the register, the old recipe will be replaced. - * If the recipe is null, an IllegalArgumentException is thrown. Otherwise, the new recipe is added to the - * register's collection of recipes. - * @param recipe A new recipe to add to the register. - */ - public void addRecipe (Recipe recipe) { - if(this.recipes.contains(recipe)) { - recipes.remove(getRecipe(recipe.getName())); - recipes.add(recipe); - } else if (recipe == null) { - throw new NullPointerException("The recipe cannot be null."); - } else { - this.recipes.add(recipe); - } + /** + * The method takes in a Recipe object. If the recipe is already in the register, the old recipe + * will be replaced. If the recipe is null, an IllegalArgumentException is thrown. Otherwise, the + * new recipe is added to the register's collection of recipes. + * + * @param recipe A new recipe to add to the register. + */ + public void addRecipe(Recipe recipe) { + if (this.recipes.contains(recipe)) { + recipes.remove(getRecipe(recipe.getName())); + recipes.add(recipe); + } else if (recipe == null) { + throw new NullPointerException("The recipe cannot be null."); + } else { + this.recipes.add(recipe); } + } - /** - * The method takes in a string with the name of a recipe and returns that recipe object if it is in the - * recipe register. If it is not found, null is returned instead. - * @param name The name of a recipe as a String. - * @return The recipe matching the provided name if it is present in the recipe register. - */ - public Recipe getRecipe(String name) { - return recipes.stream(). - filter((recipe) -> recipe.getName().equals(name)) - .findFirst().orElse(null); - } - - /** - * The method takes in a number and an IngredientsAtHand object and returns an ArrayList containing that - * number of recipes that, based on the ingredients at hand, require the fewest extra ingredients apart - * from the ones at hand. If the number of recipes in the register is fewer than the provided number, the list - * will contain as many as the register can provide. The resulting list is sorted by the number of ingredients - * required apart from those ingredients at hand. If zero recipes are requested, and empty ArrayList is returned. - * @param number Number of recipes to pick from the recipe register. - * @param atHand A IngredientsAtHand object providing a collection of the food types at hand to the user. - * @return A list of recipes of sorted by available ingredients and limited to the provided number or the - * number of recipes in the register. - */ - public ArrayList<Recipe> pickBestFits(int number, IngredientsAtHand atHand) { - if(number == 0) { - return new ArrayList<>(); - } - ArrayList<Recipe> recipes; - this.recipes.forEach(r -> r.updateIngredientStatus(atHand)); + /** + * The method takes in a string with the name of a recipe and returns that recipe object if it is + * in the recipe register. If it is not found, null is returned instead. + * + * @param name The name of a recipe as a String. + * @return The recipe matching the provided name if it is present in the recipe register. + */ + public Recipe getRecipe(String name) { + return recipes.stream() + .filter((recipe) -> recipe.getName().equals(name)) + .findFirst().orElse(null); + } - recipes = this.recipes.stream() - .sorted(Comparator.comparingInt(Recipe::getMissingIngredients)) - .limit(number).collect(Collectors.toCollection(ArrayList::new)); - return recipes; + /** + * The method takes in a number and an IngredientsAtHand object and returns an ArrayList + * containing that number of recipes that, based on the ingredients at hand, require the fewest + * extra ingredients apart from the ones at hand. If the number of recipes in the register is + * fewer than the provided number, the list will contain as many as the register can provide. The + * resulting list is sorted by the number of ingredients required apart from those ingredients at + * hand. If zero recipes are requested, and empty ArrayList is returned. + * + * @param number Number of recipes to pick from the recipe register. + * @param atHand A IngredientsAtHand object providing a collection of the food types at hand to + * the user. + * @return A list of recipes of sorted by available ingredients and limited to the provided number + * or the number of recipes in the register. + */ + public ArrayList<Recipe> pickBestFits(int number, IngredientsAtHand atHand) { + if (number == 0) { + return new ArrayList<>(); } + ArrayList<Recipe> recipes; + this.recipes.forEach(r -> r.updateIngredientStatus(atHand)); + + recipes = this.recipes.stream() + .sorted(Comparator.comparingInt(Recipe::getMissingIngredients)) + .limit(number).collect(Collectors.toCollection(ArrayList::new)); + return recipes; + } } diff --git a/src/main/resources/budgets/Archive.archive b/src/main/resources/budgets/Archive.archive index 5d60f791060cd30d347b32fc1ff332ce182e0c55..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 --- a/src/main/resources/budgets/Archive.archive +++ b/src/main/resources/budgets/Archive.archive @@ -1 +0,0 @@ -APRILreasonable