In: Computer Science
Complete the code below by finishing up the tasks detailed in the comments.
ArrayList<String> fruits = new ArrayList<>(); Scanner sc = new Scanner(System.in); String fruit = "?"; while (!fruit.isEmpty()) { // prompt the user to enter a fruit // read the fruit using "sc", saving it into variable "fruit" // convert the fruit entered to lowercase // if the fruit is NOT empty and it is a new fruit, add it to ArrayList "fruits" } // display all fruits
Java Program to read fruits into Array List and display them:
//importing packages
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
ArrayList<String> fruits = new
ArrayList<>();
Scanner sc = new Scanner(System.in);
String fruit = " ";
while (!fruit.isEmpty()) {
// prompt the user to enter a
fruit
System.out.println("Enter a fruit");
// read the fruit using "sc", saving it into variable
"fruit"
fruit=sc.nextLine();
// convert the fruit entered to
lowercase
fruit=fruit.toLowerCase();
// if the fruit is NOT empty and it is a new
fruit, add it to ArrayList "fruits"
if(!fruits.contains(fruit) &&
!fruit.isEmpty()){
fruits.add(fruit);
}
}
System.out.println("Displaying Fruits : ");
//Displaying Fruits
for(int i = 0; i < fruits.size(); i++) {
System.out.print(fruits.get(i) + "\n");
}
}
}
Screenshot code:
Output: