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 collections "fruits" } // display all fruits
Java Code
import java.util.*;
class JavaExample {
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 collections "fruits"
if(fruit!="" && fruits.indexOf(fruit)==-1){
fruits.add(fruit);
}
}
// display all fruits
System.out.println(fruits);
}
}
Screenshot of the code
Screenshot of Output
Program Logic
1) the user input isn't empty. If it's empty then it is not added to the list.
2) the indexof method returns -1 if a given item is not found in the list. This is used to find if the new fruit is unique or not. It is entered into the list only if it's unique.
Get Answers For Free
Most questions answered within 1 hours.