基于控制台的购书系统代码java
时间: 2023-08-08 22:12:30 浏览: 59
以下是一个基于控制台的购书系统的Java代码示例:
```java
import java.util.Scanner;
public class Bookstore {
private static final String[] BOOKS = {"Java Programming", "Python Cookbook", "JavaScript: The Good Parts"};
private static final double[] PRICES = {29.99, 24.99, 19.99};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to our bookstore!");
int choice = -1;
double total = 0;
while (choice != 0) {
System.out.println("\nPlease select a book:");
for (int i = 0; i < BOOKS.length; i++) {
System.out.printf("%d. %s ($%.2f)\n", i + 1, BOOKS[i], PRICES[i]);
}
System.out.println("0. Checkout");
choice = scanner.nextInt();
if (choice >= 1 && choice <= BOOKS.length) {
total += PRICES[choice - 1];
System.out.printf("You have selected %s.\n", BOOKS[choice - 1]);
} else if (choice != 0) {
System.out.println("Invalid choice. Please select again.");
}
}
System.out.printf("Your total is $%.2f. Thank you for shopping with us!\n", total);
}
}
```
该程序使用静态数组来存储书名和价格,并使用循环和条件语句来允许用户选择要购买的书籍。选择 0 时,程序会计算总价并退出。该程序可以根据需要进行扩展,例如添加库存跟踪或更复杂的价格计算。