Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code, which implements 2 arrays. The 1st array is to store flower names, and the 2nd array is to store the flower price. 

import java.util.Scanner;

public class FlowerCounter

{

    public static void main(String[] args)

    {

        String[] flowers = new String[5];

        double[] price = {.50, .75, 1.50, .50, .80};

        Scanner keyboard = new Scanner(System.in);

        System.out.println("What kind of flower would you " +

            "like to purchase? \nPetunia, Pansy, Rose," +

            " Violet, or Carnation?");

        String index = keyboard.nextLine();

        System.out.println("How many " + index +"s" + " would you like?");

        int count = keyboard.nextInt();

        double total = count * price.length;

        System.out.println("The cost for " + count  +  index  + " is " + total);             

    }        

}

I’m not able to output the associated cost with the particular flower. Can anyone tell me how to do it?

1 Answer

0 votes
by (19.7k points)

Check the code below:

import java.util.Scanner;


 

public class FlowerCounter {

public static void main(String[] args)

{

   String[] flowers = {"Petunia", "Pansy", "Rose", "Violet", "Carnation"};

   double[] price = {.50, .75, 1.50, .50, .80};

   double cost = 0;

   Scanner keyboard = new Scanner(System.in);

   System.out.println("What kind of flower would you " +

                          "like to purchase? \nPetunia, Pansy, Rose," +

                          " Violet, or Carnation?");

   String index = keyboard.nextLine();

   System.out.println("How many " + index +"s" + " would you like?");

   int count = keyboard.nextInt();

  if (index.equals("Petunia") || index.equals("petunia"))

       cost = (double)price[0] * count;

   else if (index.equals("Pansy") || index.equals("pansy"))

       cost = (double)price[1] * count;

   else if (index.equals("Rose") || index.equals("rose"))

       cost = (double)price[2] * count;

   else if (index.equals("Violet") || index.equals("violet"))

       cost = (double)price[3] * count;

   else if (index.equals("Carnation") || index.equals("carnation"))

       cost = (double)price[4] * count;

   else 

       System.out.println("wrong flower");

   System.out.println("The cost for " + count+ " "  +  index  + " is " + cost);            

}

}

Interested in Java? Check out this Java tutorial by Intellipaat. 

Related questions

0 votes
1 answer
asked Apr 14, 2021 in Java by dev_sk2311 (45k points)
0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...