Please Help me to solve the Simple Java program

The assignment is:

Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)

I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.

import java.util.Scanner;

public class Book_Discount {
  public static void main(String args[]) {
  public static final double d = 0.8;
  Scanner input = new Scanner(System.in);

  int purchases;
  double discounted_price;
  System.out.print("Enter value of purchases: ");

  purchases = input.nextInt();
  discounted_price = purchases * d; // Here discount calculation takes place

  // Displays discounted price
  System.out.println("Value of discounted price: " + discounted_price); 
  }

}

Upvotes: 0

Views: 3383

Answers (1)

Martijn Courteaux
Martijn Courteaux

Reputation: 68887

For prompting the book name as well, you write something like:

/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price

/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
    System.out.print("Name of the book? ");
    String name = scanner.nextLine();  // get the name
    System.out.print("Price of the book? ");
    double price = scanner.nextDouble(); // get the price
    scanner.nextLine(); // finish the line
    totalPrice += price; // add the price to the counter
}

/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
    totalPrice *= 0.8d;
}

/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);

Upvotes: 1

Related Questions