In: Computer Science
JAVA
You will then prompt the user to enter each grocery item and store it in your array. Afterward, the program will ask the user to enter which grocery item they are looking for in the list, and return a message back on whether it was found or not found.
(Hint: You will need two for-loops for this program - one for storing each element into the array and one for searching back through the array.) See below for example output:
Example output 1:
How many items would you like on your grocery list?
3
Enter item 1:
potato
Enter item 2:
cheesecake
Enter item 3:
bread
Welcome to your digital grocery list!
What item are you looking for?
bread
bread was found in your list!
Example output 2:
How many items would you like on your grocery list?
3
Enter item 1:
potato
Enter item 2:
cheesecake
Enter item 3:
bread
Welcome to your digital grocery list!
What item are you looking for?
muffins
muffins not found.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// taking user input for number of items
System.out.println("How many items would you like on your grocery
list?");
int n = sc.nextInt();
String[] items = new String[n]; // Taking n items into array
for(int i=0; i<n; i++)
{
System.out.println("Enter item " + i + ": ");
items[i] = sc.next();
}
System.out.println("Welcome to your digital grocery list!");
System.out.println("What item are you looking for?");
String item = sc.next(); // taking item to be searched
boolean found = false;
for(String s: items) // searching
{
if(s.equals(item)) // if found, printing so
{
found = true;
System.out.println(item + " found in your list!");
break;
}
}
if(!found) // otherwise prints not found
System.out.println(item + " not found.");
}
}
// Please up vote.