2012-04-15 49 views
0

作業爲:請幫我解決簡單的Java程序

編寫一個程序,爲在XYZ書店購買任何兩本書的會員提供20%的折扣。 (提示:使用常量變量可享受20%的折扣。)

我已經做了編碼,但不能提示書名,然後顯示折扣價。請參閱下面的代碼並根據需要進行修改。

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); 
    } 

} 
+1

哪裏是試圖得到這本書的名字的代碼?你正在設法讀取一個int,所以你應該能夠弄清楚如何讀取一個字符串。你還有什麼其他問題? – Mat 2012-04-15 09:27:27

+2

大概是作業。 – 2012-04-15 09:27:52

+0

你唯一缺少的是'scanner.nextLine()'。 – 2012-04-15 09:35:52

回答

1

用於提示書的名字,以及,你寫的東西,如:

/* 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); 
+0

許多很多謝謝...它真的幫助 – 2012-05-18 17:23:58