java - 请帮我解决简单的Java程序

标签 java user-input java.util.scanner

任务是:

编写一个程序,为在 XYZ 书店购买任意两本书的成员(member)提供 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); 
  }

}

最佳答案

为了提示书名,您可以编写如下内容:

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

关于java - 请帮我解决简单的Java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10160885/

相关文章:

java - 我的代码中发生了一些奇怪的交互,但我找不到解决方案

java - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException 未知列

java - 如何使用 Spring ClientResponse 使用 Map?

string - 为什么从标准输入读取用户输入时我的字符串不匹配?

java - 只需一个 Setter 即可实现多个输入

java - For 循环中的多个扫描仪输入

java - 使用java将原始xml字符串直接发送到soap服务

javax.net.ssl.SSLHandshakeException : null cert chain java error

java - 保存单向一对多映射时,Hibernate 在外键字段中插入空值

使用扫描仪时出现 java.util.NoSuchElementException