In: Computer Science
Mr Allen is selling 5 sets of western food in restaurant. He wants to build a food ordering system. So if the system has added 5 sets of western food inside the text file, how to use search function to search the foods from the text file by using(( JAVA )) and display it ?
CODE (AS TEXT) ->
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
public class Solution3
{
public static void main(String[] args) throws
Exception
{
File file = new
File("C:\\Users\\ishu\\Desktop\\menu.txt"); // creating a new file
object to read the input file
Scanner s=new Scanner(file); //
scanner object is created which reads the file
ArrayList<String> menu=new
ArrayList<String>(); // list to store the menu items
String searchItem="Cheesy Rice and
Broccoli Casserole";
while(s.hasNextLine()) // loop
terminates when there is no new line in the file
{
String
nextItem=s.nextLine(); // next item of the menu (read from text
file)
menu.add(nextItem); // the read item is added in the list
if(searchItem.contentEquals(nextItem)) //if the desired item is
found
System.out.println("Your item : " +searchItem+ "
is found in the menu");
}
System.out.println("The entire menu
is : "); // to print the entire menu
System.out.println(menu);
}
}
OUTPUT (ALONG WITH TEXT FILE) ->
CODE (IN THE CODE SNIPPET) ->
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
public class Solution3
{
public static void main(String[] args) throws Exception
{
File file = new File("C:\\Users\\ishu\\Desktop\\menu.txt"); // creating a new file object to read the input file
Scanner s=new Scanner(file); // scanner object is created which reads the file
ArrayList<String> menu=new ArrayList<String>(); // list to store the menu items
String searchItem="Cheesy Rice and Broccoli Casserole";
while(s.hasNextLine()) // loop terminates when there is no new line in the file
{
String nextItem=s.nextLine(); // next item of the menu (read from text file)
menu.add(nextItem); // the read item is added in the list
if(searchItem.contentEquals(nextItem)) //if the desired item is found
System.out.println("Your item : " +searchItem+ " is found in the menu");
}
System.out.println("The entire menu is : "); // to print the entire menu
System.out.println(menu);
}
}
NOTE ->
(i) i gave you code twice once as text and once in the code snippet because some students complaint about adding of extra invisible character in code , so i gave you code twice once a code and once as text , whatever works for you.
(ii) please change the name and location of the text file according to your file otherwise it may give you error.
I HOPE YOU WILL GET IT..............YOUR RESPONSE WILL BE HIGHLY APPRECIATED.