You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java输入非法值时触发while无限循环问题咨询

程序概述

要求用户输入短语,再输入一个索引值,程序会旋转打乱短语,直到该索引对应的字符移动到字符串的首位(索引0位置)。输入环节需持续校验直到用户输入合法整数,短语打乱完成后询问用户是否需要再次打乱,若选择是则按新输入的索引重新打乱,若选择否则输出最终结果并结束程序。

原代码问题说明

当前代码的while循环会无限运行,预期逻辑为:先校验输入是否为整数,是则退出循环继续执行,否则持续询问直到获取合法整数,同时需校验输入整数是否在合法索引范围内。

问题根因
  • 非整数输入未被消费:当用户输入非整数内容时,代码仅输出错误提示,未清除Scanner缓冲区中的非法输入,导致每次循环都读取到同一个非法值,进入死循环。
  • 索引校验逻辑位置错误:范围校验的分支被放在了「输入非整数」的逻辑下,永远不会触发;且拿到整数输入后直接跳出循环,没有做范围校验,完全不符合需求。
  • 索引范围判断逻辑错误:合法索引的区间是[0, 字符串长度-1],原代码判断条件仅判断了大于长度的情况,未覆盖小于0的场景,且判断阈值未减1,会出现等于长度的非法索引被放行的问题。
修复后完整代码
import java.util.Scanner;

public class PJ {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String phrase;
        String phraseMut;

        System.out.println("Enter your word or phrase: ");
        phrase = scan.nextLine();
        phraseMut = phrase;
        System.out.println();

        while (true) {
            int index = 0;
            // 校验合法索引输入
            while (true) {
                System.out.println("Enter an Integer: ");
                if (scan.hasNextInt()) {
                    index = scan.nextInt();
                    scan.nextLine(); // 消费掉换行符
                    // 校验索引范围
                    if (index >= 0 && index < phraseMut.length()) {
                        break;
                    } else {
                        System.out.println("Error: Index is out of bounds.");
                        System.out.printf("Please enter an integer between 0 and %d.%n", phraseMut.length()-1);
                    }
                } else {
                    // 消费掉非法输入
                    String invalidInput = scan.nextLine();
                    System.out.println("Error: Index is not Integer.");
                }
            }

            System.out.println();
            System.out.println("Rotating phrase to bring index " + index + " to the front. . .");

            // 执行旋转
            for (int i = 0; i < index; i++) {
                phraseMut = phraseMut.substring(1) + phraseMut.charAt(0);
                System.out.println(phraseMut);
            }

            // 询问是否再次打乱
            System.out.println("\nDo you want to rotate again? (y/n)");
            String choice = scan.nextLine().trim().toLowerCase();
            if (!"y".equals(choice)) {
                System.out.println("Final result: " + phraseMut);
                break;
            }
        }
        scan.close();
    }
}
修复说明
  • 补充了非法输入消费逻辑:非整数输入时调用nextLine()清除缓冲区,避免死循环。
  • 调整了索引校验逻辑的位置:拿到整数输入后先判断范围,合法才退出输入循环,否则提示越界重新输入。
  • 优化了索引范围判断逻辑:覆盖了小于0和大于等于字符串长度的所有非法场景,提示信息明确标注合法输入范围。
  • 补充了重复旋转的交互逻辑:旋转完成后询问用户是否继续,符合需求要求。
  • 优化了旋转逻辑的代码写法:简化了substring的参数,避免引用原字符串长度导致的潜在错误。

内容的提问来源于stack exchange,提问作者L. Jacob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:06:03