Question

Complete the code below by finishing up the tasks detailed in the comments. ArrayList<String> fruits =...

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

Homework Answers

Answer #1

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

  • *The while loop runs until the user input, which is stored in the fruit variable, is not empty.
  • *During each while loop, user input is asked and stored in the fruit variable.
  • *The fruit name is then converted to lowercase.
  • *Then the if loop checks whether

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.

  • *Finally all the items in the list "fruits" is displayed.
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
main The main method instantiates an ArrayList object, using the Car class. So, the ArrayList will...
main The main method instantiates an ArrayList object, using the Car class. So, the ArrayList will be filled with Car objects. It will call the displayMenu method to display the menu. Use a sentinel-controlled loop to read the user’s choice from stdin, call the appropriate method based on their choice, and redisplay the menu by calling displayMenu. Be sure to use the most appropriate statement for this type of repetition. displayMenu Parameters:             none Return value:          none Be sure to use...
x86 irvine library assembly code Write a complete program that: 1. Prompt the user to enter...
x86 irvine library assembly code Write a complete program that: 1. Prompt the user to enter 10 numbers. 2. save those numbers in a 32-bit integer array. 3. Print the array with the same order it was entered. 3. Calculate the sum of the numbers and display it. 4. Calculate the mean of the array and display it. 5. Rotate the members in the array forward one position for 9 times. so the last rotation will display the array in...
Complete the program to calculate and print the circumference and area of a circle, rounded to...
Complete the program to calculate and print the circumference and area of a circle, rounded to the nearest tenth (1 decimal place). The starter code already prompts the user and takes in the radius as a double-value input. You need to do the calculations and print the results. I recommend using the printf() command (described in chapter 3 of the book) to print the results with the correct rounding. import java.util.Scanner; class Circle { static Scanner sc = new Scanner(System.in);...
TO BE DONE IN JAVA Your task is to complete the AddTime program so that it...
TO BE DONE IN JAVA Your task is to complete the AddTime program so that it takes multiple sets of hours, minutes and seconds from the user in hh:mm:ss format and then computes the total time elapsed in hours, minutes and seconds. This can be done using the Time object already given to you. Tasks: Complete addTimeUnit() in AddTime so that it processes a string input in hh:mm:ss format and adds a new Time unit to the ArrayList member variable....
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code to initialize the CustomerAccountsDB database table and add a set of customer accounts is provided. Finish the code in these 3 methods in CustomerAccountDB.java to update or query the database: -purchase(double amountOfPurchase) -payment(double amountOfPayment) -getCustomerName() Hint: For getCustomerName(), look at the getAccountBalance() method to see an example of querying data from the database. For the purchase() and payment() methods, look at the addCustomerAccount() method...
Task #4 Calculating the Mean Now we need to add lines to allow us to read...
Task #4 Calculating the Mean Now we need to add lines to allow us to read from the input file and calculate the mean. Create a FileReader object passing it the filename. Create a BufferedReader object passing it the FileReader object. Write a priming read to read the first line of the file. Write a loop that continues until you are at the end of the file. The body of the loop will: convert the line into a double value...
Finish the CustomerAccountTransactions program that reads customer accounts receivable data from a file and then applies...
Finish the CustomerAccountTransactions program that reads customer accounts receivable data from a file and then applies a series of transactions to the accounts. Its main() method uses the CustomerAccounts class to manage a collection of CustomerAccount objects: reading customer accounts data & transactions, and obtaining a String showing the customer accounts data after the operations are complete. You will need to complete the readCustomerAccounts () and applyTransactions() methods in the CustomerAccounts class. First, please fill in your name in the...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import java.io.*; //This imports input and output (io) classes that we use 3 //to read and write to files. The * is the wildcard that will 4 //make all of the io classes available if I need them 5 //It saves me from having to import each io class separately. 6 /** 7 This program reads numbers from a file, calculates the 8 mean (average)...
In Chapter 9, you created a Contestant class for the Greenville Idol competition. The class includes...
In Chapter 9, you created a Contestant class for the Greenville Idol competition. The class includes a contestant’s name, talent code, and talent description. The competition has become so popular that separate contests with differing entry fees have been established for children, teenagers, and adults. Modify the Contestant class to contain a field that holds the entry fee for each category, and add get and set accessors. Extend the Contestant class to create three subclasses: ChildContestant, TeenContestant, and AdultContestant. Child...