
Java选择结构练习——小明可以购买哪些物品
5星
- 浏览量: 0
- 大小:None
- 文件类型:DOCX
简介:
本练习旨在通过实例讲解Java中的选择结构语法和应用。具体场景设定为分析小明手头的钱能够买哪些特定商品,涵盖if、else等语句的实际操作。适合初学者理解和掌握条件判断逻辑。
本段落将指导读者学习 Java 中的选择结构,并通过实践案例掌握使用 switch 条件语句进行运算操作的方法。
在本案例中,我们将实现一个智能购物计算小程序。一家商店中有五种商品:书本、铅笔、橡皮、可乐和零食。它们的价格如下表所示:
| 商品名称 | 价格(元) |
| --- | --- |
| 书本 | 12 |
| 铅笔 | 1 |
| 橡皮 | 2 |
| 可乐 | 3 |
| 零食 | 5 |
假如小明带了20元,且必须购买一本书。那么剩余的钱还可以买哪些商品?可以购买多少件这些商品?购买完后又能剩下多少钱?
案例目标包括:
- 分析智能购物程序的实现思路
- 根据思路独立完成“智能购物”的源代码编写、编译及运行
- 掌握在程序中使用 switch 条件语句进行运算操作
实现此功能,我们需要先定义五种商品的价格,并打印各个商品价格以及带的钱数。用户选择需要购买的商品序列号后,我们将使用 switch 条件语句判断要买哪一件商品并计算可以购买多少其他商品和剩余多少钱。
以下是智能购物的代码:
```java
package chapter0202;
import java.util.Scanner;
public class shopping {
public static void main(String[] args) {
int pencil = 1; // 铅笔价格
int rubber = 2; // 橡皮价格
int cola = 3; // 可乐价格
int book = 12; // 书本价格
int snacks = 5; // 零食价格
System.out.println(书本的价格为 + book + 元,您总共有 20 元);
System.out.println(1.铅笔的价格为: + pencil + 元);
System.out.println(2.橡皮的价格为: + rubber + 元);
System.out.println(3.可乐的价格为: + cola + 元);
System.out.println(4.零食的价格为: + snacks + 元);
Scanner sc1 = new Scanner(System.in);
System.out.print(请输入其他需要购买商品的序列号:);
int id = sc1.nextInt();
switch (id) {
case 1:
int pencilmoney = 20 - book;
int pencilsum = pencilmoney / pencil;
int pencilsurplus = pencilmoney % pencil;
System.out.println(购买完书本后还可以购买铅笔 + pencilsum + 个,还剩 + pencilsurplus + 元);
break;
case 2:
int rubbermoney = 20 - book;
int rubbersum = rubbermoney / rubber;
int rubbersurplus = rubbermoney % rubber;
System.out.println(购买完书本后还可以购买橡皮 + rubbersum +个,还剩 +rubbersurplus + 元);
break;
case 3:
int colamoney = 20 - book;
int colasum = colamoney / cola;
int colasurplus = colamoney % cola;
System.out.println(购买完书本后还可以购买可乐 +colasum +个,还剩 +colasurplus + 元);
break;
case 4:
int snacksmoney = 20 - book;
int snackssum = snacksmoney / snacks;
int snackssurplus = snacksmoney % snacks;
System.out.println(购买完书本后还可以购买零食 +snackssum +个,还剩 +snackssurplus + 元);
break;
}
}
}
```
通过这个案例,我们学习了如何使用 switch 条件语句进行运算操作,并掌握了智能购物程序的实现思路。
全部评论 (0)


