无限循环:while True+if...break(打破循环) 用法

本文通过一个简单的Python代码示例,展示了如何使用while循环和条件判断语句控制程序流程。具体介绍了如何让程序在满足特定条件下停止运行,如当输入特定字符串时退出循环。
while True:
    p = input('请输入你的名字')
    if p =='小龙女':
        break
print('可以进入古墓')   

public class Todolist { import java.io.DataInputStream; import java.io.InputStream; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class SeverReaderThread extends Thread{ //下面是有参构造器,在这里再创建一个csoc接收处理 private Socket csoc; // 使用 HashMap 存储任务 private static HashMap<Integer, String> tasks = new HashMap<>(); private static int nextId = 1; private static int maxTasks; private static ArrayList<String> invalidInputs = new ArrayList<>(); //使用数组存储任务,定义为static,静态代码块:初始化最大任务数 static { Scanner sc = new Scanner(System.in); maxTasks = sc.nextInt(); // 吃掉换行符 sc.nextLine(); System.out.println("确定好了一共 " + maxTasks + " 条任务哦!"); } public SeverReaderThread(Socket csoc){ //把送进来的csoc管道给到上面的socket,把当前客户管道交给了一个独立的线程对象。 this.csoc=csoc; } @Override public void run() { //进阶任务:处理异常,得到输入流,包装成数据输入流 try{ InputStream is=csoc.getInputStream(); DataInputStream dis=new DataInputStream(is); while(true){ String msg=dis.readUTF(); //基础任务和进阶任务,一共八个功能(有一个是defult里面记录用户错误输入的需求) // 客户端发送的消息一次性以空格拆分为最多三部分 // parts[0]=命令, [1]=ID, [2]=内容(可选) String[] parts = msg.split(" ", 3); // 第一部分:命令名 String command = parts[0]; // 第二部分:任务编号 int taskId = Integer.parseInt(parts[1]); // 第三部分:任务内容(可能没有) String content = (parts.length > 2) ? parts[2] : ""; switch (command) { case "add": if (tasks.size() >= maxTasks) { System.out.println("任务列表已满!"); } else { tasks.put(taskId, content); System.out.println("已添加 -> ID:" + taskId + ", 内容:'" + content + "'"); if (taskId >= nextId) { nextId = taskId + 1; } } break; case "list": System.out.println("--- 当前任务列表 ---"); if (tasks.isEmpty()) { System.out.println("暂无任务"); } else { for (int id : tasks.keySet()) { System.out.println(id + ": " + tasks.get(id)); } } break; case "modify": tasks.put(taskId, content); System.out.println("任务" + taskId + "已修改为: '" + content + "'"); break; case "delete": tasks.remove(taskId); System.out.println("任务" + taskId + "已删除"); break; case "clear": tasks.clear(); nextId = 1; System.out.println("所有任务已清空"); break; case "count": int count = tasks.size(); System.out.println("当前共有 " + count + " 个任务(最多可存 " + maxTasks + " 条)"); break; case "help": System.out.println("==== 帮助菜单 ===="); System.out.println("可用命令如下:"); System.out.println(" add 1 买菜 —— 添加ID=1的任务"); System.out.println(" modify 2 新内容 —— 修改ID=2的任务"); System.out.println(" delete 3 —— 删除ID=3的任务"); System.out.println(" list —— 查看全部任务"); System.out.println(" clear —— 清空所有任务"); System.out.println(" count —— 显示任务总数"); System.out.println(" help —— 显示此帮助信息"); break; default: // 把用户输入的原始消息保存到列表中 invalidInputs.add(msg); System.out.println("未知命令: '" + command + "'"+"抱歉" + "我目前只有这么多功能."); // 打印当前已记录多少条无效输入 System.out.println("但是我当前已记录 " + invalidInputs.size() + " 条功能之外的需求" + "我会努力增加的"); } } } catch (Exception e) { throw new RuntimeException(e); } } } }上面是我原有的代码,在我原有代码上面修改,变成一个完整的程序,尽量少的修改,简单初学这可以学会,提供最终完整答案,表明修改了哪里,只用java,每一行都解释
10-18
package game.game2048; /** * @BelongsProject: TimeGame * @BelongsPackage: Demo.game * @Author: 土里埋埋埋埋埋 * @CreateTime: 2025-07-31 11:51 * @Description: 游戏界面 * @Version: 1.0 */ import game.game2048.game.Direction; import game.game2048.game.Game; import java.sql.SQLException; import java.util.List; import java.util.Random; import java.util.Scanner; public class ConsoleUI { private Scanner scanner; private GameDAO gameDAO; private int currentUserId; public ConsoleUI() throws SQLException { scanner = new Scanner(System.in); gameDAO = new GameDAO(); currentUserId = -1; } public void start() throws SQLException { while (true) { if (currentUserId == -1) { showLoginMenu(); } else { showMainMenu(); } } } //获取登录菜单 private void showLoginMenu() { System.out.println("=== 2048 游戏 ==="); System.out.println("1. 登录"); System.out.println("2. 注册"); System.out.println("3. 退出"); System.out.print("请选择: "); int choice = scanner.nextInt(); scanner.nextLine(); try { switch (choice) { case 1: login(); break; case 2: register(); break; case 3: System.exit(0); default: System.out.println("无效选择!"); } } catch (SQLException e) { System.out.println("数据库错误: " + e.getMessage()); } } //登录界面 private void login() throws SQLException { System.out.print("用户名: "); String username = scanner.nextLine(); System.out.print("密码: "); String password = scanner.nextLine(); int userId = gameDAO.authenticateUser(username, password); if (userId != -1) { currentUserId = userId; captcha(); System.out.println("登录成功!"); } else { System.out.println("用户名或密码错误!"); } } //注册界面 private void register() throws SQLException { System.out.print("用户名: "); String username = scanner.nextLine(); System.out.print("密码: "); String password = scanner.nextLine(); if (gameDAO.registerUser(username, password)) { System.out.println("注册成功!"); } else { System.out.println("注册失败,用户名可能已存在!"); } } //登录验证 public void captcha() { while (true) { Scanner sc = new Scanner(System.in); String code = getCode(); System.out.println("生成的验证码为:" + code); System.out.print("请输入验证码:"); String userInput = sc.next(); if (validateCaptcha(code, userInput)) { System.out.println("验证码正确!"); break; } else { System.out.println("验证码错误!"); } } } public static String getCode() { String box = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuilder captcha = new StringBuilder(); String codeBox = ""; for (int i = 0; i < 4; i++) { int index = random.nextInt(box.length()); char c = box.charAt(index); codeBox += c; } return codeBox; } public static boolean validateCaptcha(String captcha, String userInput) { return captcha.equalsIgnoreCase(userInput); } //游戏主菜单 private void showMainMenu() throws SQLException { System.out.println("=== 主菜单 ==="); System.out.println("1. 开始新游戏"); System.out.println("2. 加载存档"); System.out.println("3. 查看排行榜"); System.out.println("4. 查看历史记录"); System.out.println("5. 退出登录"); System.out.println("6. 退出游戏"); System.out.print("请选择: "); int choice = scanner.nextInt(); scanner.nextLine(); System.out.println(); switch (choice) { case 1: startGame(); break; case 2: loadGame(); break; case 3: showRankings(); break; case 4: showUserHistory(); break; case 5: currentUserId = -1; System.out.println("已退出登录"); break; case 6: System.exit(0); default: System.out.println("无效选择!"); } } private void startGame() throws SQLException { while (true) { Game Game = new Game(); playGame(Game); System.out.println("请选择是否重新开始: 1 - 重新开始 其他 - 返回菜单"); int res = scanner.nextInt(); if (res == 1) { Game.resetGame(); } else { showMainMenu(); break; } } } private void startTimeGame() throws SQLException { while (true) { Game easyGame = new Game(); playGame(easyGame); System.out.println("请选择是否重新开始: 1 - 重新开始 其他 - 返回菜单"); int res = scanner.nextInt(); if (res == 1) { easyGame.resetGame(); } else { showMainMenu(); break; } } } //游戏存档 private void loadGame() throws SQLException { List<String> saves = gameDAO.getUserSaves(currentUserId); if (saves.isEmpty()) { System.out.println("没有找到存档!"); return; } System.out.println("您的存档:"); for (String save : saves) { System.out.println(save); } System.out.print("输入存档ID: "); int saveId = scanner.nextInt(); scanner.nextLine(); GameDAO.GameSave gameSave = gameDAO.loadGame(saveId); if (gameSave != null) { Game game = new Game(gameSave.boardState, gameSave.score); playGame(game); } else { System.out.println("加载存档失败!"); } } //游戏规则 private void playGame(Game game) throws SQLException { List<String> maxscore = gameDAO.maxscore(); while (!game.isGameOver()) { System.out.print("当前分数: " + game.getScore()); System.out.print("\t最高分数: "); for (String rank : maxscore) { System.out.print(rank); } System.out.println(); displayBoard(game.getBoard()); System.out.println("操作: w() s() a() d() q(退出) x(存档)"); System.out.print("输入操作: "); String input = scanner.nextLine().toLowerCase(); if (input.equals("q")) { return; } else if (input.equals("x")) { System.out.print("输入存档名称: "); String saveName = scanner.nextLine(); gameDAO.saveGame(currentUserId, saveName, game.getBoardState(), game.getScore()); System.out.println("游戏已保存!"); return; } else { Direction direction = null; switch (input) { case "w": direction = Direction.UP; break; case "s": direction = Direction.DOWN; break; case "a": direction = Direction.LEFT; break; case "d": direction = Direction.RIGHT; break; default: System.out.println("操作无效"); continue; } game.move(direction); } } displayBoard(game.getBoard()); System.out.println("游戏结束! 最终分数: " + game.getScore()); gameDAO.saveScore(currentUserId, game.getScore()); } //打印地图 private void displayBoard(int[][] board) { for (int i = 0; i < 4; i++) { System.out.print(""); for (int j = 0; j < 4; j++) { if (board[i][j] == 0) { System.out.print("\t▢"); } else { System.out.print("\t"); System.out.print(board[i][j]); } } System.out.println(); } } //排行榜 private void showRankings() throws SQLException { System.out.println("=== 排行榜 ==="); List<String> globalRanking = gameDAO.getGlobalRanking(); for (String rank : globalRanking) { System.out.println(rank); } } //游戏历史 private void showUserHistory() throws SQLException { System.out.println("=== 游戏历史 ==="); List<String> userHistory = gameDAO.getUserHistory(currentUserId); if (userHistory.isEmpty()) { System.out.println("暂无记录"); } else { for (String history : userHistory) { System.out.println(history); } } } }
08-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值