Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi I am making a program that reads recipes.txt by using FileIO and scanner whic

ID: 3771465 • Letter: H

Question

Hi I am making a program that reads recipes.txt by using FileIO and scanner which looks like below

-----------------------------------------------------------------------------------------------------------------

4
Chocolate chip cookies
flour, sugar, oil, butter, vanilla, chocolate chips
mix all ingredients, make cookies, bake 10 min at 350 degrees
Pesto
1 C basil, 1/2 C parmesan cheese, 1/3 C olive oil, 1/4 C walnuts, 1 clove garlic, salt and pepper to taste
mix all ingredients except cheese in a food processor, chop for 1 minute, add cheese and enjoy
PANCAKES
flour, eggs, milk, baking powder, salt, cooking oil
mix all ingredients (except oil), add oil to skillet, pour batter for each pancake, cook one side then flip when bubbles appear
CREPE
2 eggs, 1C flour, 1/2 C milk, 1/2 C water, 1/2 t salt, 2 T butter
whisk flour, salt, and eggs; add milk and water; pour 1/4 C in small oiled skillet and coat bottom with batter, cook until light brown (~2 minutes) and flip.

---------------------------------------------------------------------------------------------------------------------------------

the number of the first line indicates ArrayList.size of recipes.

the class recipe has 3 fields = recipe name , ingridients, instructions.
I want to read off from file and store it into string values.

How to improve the code below?????
public static void readFromFile(String fileName){
       File recipeFile = new File(fileName);
       try {
           Scanner recipeData = new Scanner (recipeFile);
           String recipeName = recipeData.nextLine();
  
       }catch(FileNotFoundException e){
          
       }

Explanation / Answer

import java.util.Scanner;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;

public class ReadFromFile{
public static void main(String[] args){
       String filename ="file.txt"
File recipeFile = new File(filename);
try {
Scanner recipeData = new Scanner (recipeFile);
int num_recipes = Integer.parseInt(recipeData.nextLine());

for(int i=0;i<num_recipes;i++)
{
    String recipeName = recipeData.nextLine();
    String[] ingredients = recipeData.nextLine().split(", ");
    String[] instructions = recipeData.nextLine().split(", ");
    System.out.println(recipeName);
}
  
}catch(FileNotFoundException e){
System.out.println("File not Found");
}
}
}