您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 Java 中,While 循环是一种基本的控制结构,用于在满足特定条件时重复执行代码块
import java.util.Scanner;
public class InventorySystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int inventory = 100; // 初始库存为100
int itemCount = 0; // 已售出的商品数量
while (inventory > 0) {
System.out.println("当前库存:" + inventory);
System.out.print("请输入要购买的商品数量:");
int quantity = scanner.nextInt();
if (quantity > 0) {
if (inventory >= quantity) {
inventory -= quantity;
itemCount += quantity;
System.out.println("购买成功!已售出商品数量:" + itemCount);
} else {
System.out.println("库存不足,无法购买。");
}
} else {
System.out.println("请输入一个正数。");
}
}
System.out.println("库存已售罄!");
}
}
import java.util.Scanner;
public class StudentGradeSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int studentCount = 0; // 学生数量
int totalScore = 0; // 总分数
while (studentCount < 10) { // 假设有10个学生
System.out.println("请输入学生" + (studentCount + 1) + "的分数:");
int score = scanner.nextInt();
if (score >= 0 && score <= 100) {
totalScore += score;
studentCount++;
} else {
System.out.println("分数必须在0到100之间,请重新输入。");
}
}
System.out.println("所有学生的平均分数为:" + (totalScore / studentCount));
}
}
这些案例展示了如何在实际项目中使用 While 循环来处理用户输入、计算和更新数据。当然,实际项目中的需求可能更加复杂,但 While 循环的基本用法是相似的。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。