Вызов случайного имени из текстового файла - PullRequest
0 голосов
/ 04 ноября 2019

Я пытаюсь для проекта кодировать гамбургер, который производит 3 разных гамбургера, используя RMI. На данный момент у меня большие проблемы с кодированием класса, в котором я выбрал, какой бургер (должен быть сделан случайным образом) создать.

У меня есть следующий код:

RecipeReader:

    package burgerbar.model.mediator;

import burgerbar.model.domain.Recipe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;


public class RecipeReader implements RecipeProvider
{
  private String filename;


  public RecipeReader(String filename)
  {
    this.filename = filename;
  }


  @Override public synchronized Recipe getRecipeById(String id)
      throws FileNotFoundException, IllegalStateException
  {
    String line = null;
    try
    {
      Recipe recipe = null;
      File file = new File("C:\\Users\\Aagaard\\Desktop\\recipes.txt");
      Scanner in = new Scanner(file);
      while (in.hasNext())
      {
        line = in.nextLine(); // Read a line
        String[] token = line.split(";");
        String recipeId = token[0].trim();
        if (recipeId.equalsIgnoreCase(id))
        {
          recipe = convertToRecipe(line);
          break;
        }
      }
      in.close();
      return recipe;
    }
    catch (FileNotFoundException e)
    {
      throw e;
    }
    catch (Exception e)
    {
      throw new IllegalStateException("Wrong formatted file: " + line);
    }
  }


  @Override public synchronized Recipe getRecipeByName(String name)
      throws FileNotFoundException, IllegalStateException
  {
    String line = null;
    try
    {
      Recipe recipe = null;
      File file = new File(filename);
      Scanner in = new Scanner(file);
      while (in.hasNext())
      {
        line = in.nextLine(); // Read a line
        String[] token = line.split(";");
        String recipeName = token[1].trim();
        if (recipeName.equalsIgnoreCase(name))
        {
          recipe = convertToRecipe(line);
          break;
        }
      }
      in.close();
      return recipe;
    }
    catch (FileNotFoundException e)
    {
      throw e;
    }
    catch (Exception e)
    {
      throw new IllegalStateException("Wrong formatted file: " + line);
    }
  }

    @Override public synchronized void updateRecipe(Recipe recipe)
      throws FileNotFoundException, IllegalStateException
  {
    String line = null;
    try
    {
      ArrayList<Recipe> recipes = new ArrayList<>();
      File file = new File(filename);
      Scanner in = new Scanner(file);
      boolean updated = false;
      while (in.hasNext())
      {
        line = in.nextLine(); // Read a line
        String[] token = line.split(";");
        String recipeId = token[0].trim();
        if (recipeId.equalsIgnoreCase(recipe.getId()))
        {
          recipes.add(recipe);
          updated = true;
        }
        else
        {
          recipes.add(convertToRecipe(line));
        }
      }
      if (!updated)
      {
        recipes.add(recipe);
      }
      in.close(); // Close the file

      PrintWriter out = new PrintWriter(file);
      for (int i = 0; i < recipes.size(); i++)
      {
        out.println(convertFromRecipe(recipes.get(i)));
      }
      out.close();
    }
    catch (FileNotFoundException e)
    {
      throw e;
    }
    catch (Exception e)
    {
      throw new IllegalStateException("Wrong formatted file: " + line);
    }
  }

  private String convertFromRecipe(Recipe recipe)
  {
    String recipeId = recipe.getId();
    String name = recipe.getName();
    String ingredientsString = "";
    String[] ingredients = recipe.getIngredients();
    for (int j = 0; j < ingredients.length; j++)
    {
      ingredientsString += ingredients[j];
      if (j < ingredients.length - 1)
      {
        ingredientsString += "; ";
      }
    }
    return (recipeId + "; " + name + "; " + ingredientsString);
  }

  private Recipe convertToRecipe(String recipeString)
  {
    String[] token = recipeString.split(";");
    String recipeId = token[0].trim();
    String name = token[1].trim();
    String[] ingredients = new String[token.length - 2];
    for (int i = 2; i < token.length; i++)
    {
      ingredients[i - 2] = token[i].trim();
    }
    return new Recipe(recipeId, name, ingredients);
  }
}

RecipeProvider:

package burgerbar.model.mediator;
import burgerbar.model.domain.Recipe;

public interface RecipeProvider
{

  public Recipe getRecipeById(String id) throws Exception;

  public Recipe getRecipeByName(String name) throws Exception;

  public void updateRecipe(Recipe recipe) throws Exception;
}

Burger: пакет burgerbar.model.domain;

import java.io.Serializable;

public class Burger implements Serializable
{
   private static final long serialVersionUID = 1L;
   private String name;

   public Burger(String name)
   {
      this.name = name;
   }

   public String getName()
   {
      return name;
   }

   @Override
   public String toString()
   {
      return "Burger: " + name;
   }
}

Рецепт:

package burgerbar.model.domain;

import java.util.Arrays;

public class Recipe
{
  private String id;
  private String name;
  private String[] ingredients;

  public Recipe(String id, String name, String... ingredients)
  {
    this.id = id;
    this.name = name;
    this.ingredients = ingredients;
  }

  public String getId()
  {
    return id;
  }

  public String getName()
  {
    return name;
  }

  public String[] getIngredients()
  {
    return ingredients;
  }

  public Burger createBurger()
  {
    return new Burger(name);
  }

  @Override public String toString()
  {
    return "Recipe{" + "id='" + id + '\'' + ", name='" + name + '\''
        + ", ingrediences=" + Arrays.toString(ingredients) + '}';
  }
}

Мой текстовый файл:

1; Hamburger; 4 inch bun; Tomato; Onion; Beef; Lettuce; Cucumber; Ketchup
2; Cheese burger; 5 inch bun; Tomato; Onion; Cheese; Beef; Lettuce; Cucumber; Ketchup
3; Veggie burger; 5 inch bun; Green asparagus; Tomato; Grilled Portobello Mushroom; Onion; Veggie Patty; Lettuce; Cucumber; Vegan mayo

1 Ответ

0 голосов
/ 04 ноября 2019

Я предполагаю, что вы хотите предложить случайные из любых трех гамбургеров из вашего файла.

Чтобы достичь этого, вам сначала нужно создать List<Recipe>, как только вы прочитаете рецепт из файла, поместите рецептобъект в этом списке. Когда у вас есть список рецептов, вы можете получить случайный рецепт, используя что-то вроде ниже.

listOfRecipe.get(new Random().nextInt(listOfRecipe.size()));

Надеюсь, это поможет.

...