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

Java排序算法while循环输入异常:输入首个元素后程序终止

问题原因及解决办法

问题原因

  1. 非整数输入触发未捕获异常:代码中使用sc.nextInt()读取输入,若输入内容不是合法整数(比如字母、小数、特殊符号),会直接抛出InputMismatchException,且未做异常处理,程序会直接终止。
  2. 在线编译环境输入规则限制:部分在线编译器要求一次性提交所有输入内容(包括终止符-1),如果仅输入单个元素就提交,程序会因等待输入超时被强制终止。

解决办法

1. 添加输入异常处理

修改输入循环部分,捕获输入异常,提示用户输入合法整数,并清空错误输入缓存,避免后续读取受影响:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.InputMismatchException;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> my_array = new ArrayList<Integer>();
        while (true) {
            System.out.println("Enter your input to add to the list. Type in '-1' to finish adding. ");
            try {
                int user_in = sc.nextInt();
                if (user_in == -1) {
                    break;
                } else {
                    my_array.add(user_in);
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入合法的整数!");
                sc.next(); // 清空错误输入的缓存
            }
        }
        System.out.println(sort(my_array));
        sc.close(); // 关闭Scanner资源
    }

    public static ArrayList<Integer> sort(ArrayList<Integer> arr) {
        for (int i = 1; i < arr.size(); i++) {
            int key = arr.get(i);
            int j = i;
            while (j > 0 && arr.get(j-1) > arr.get(j)) {
                arr.set(j, arr.get(j-1));
                j--;
            }
            arr.set(j, key);
        }
        return arr;
    }
}

2. 适配在线编译环境

如果使用在线编译器,一次性输入所有需要添加的元素,最后输入-1结束。例如:

5
3
7
-1

或者用空格分隔所有输入:

5 3 7 -1

额外说明

你的插入排序逻辑是正常的,不会导致输入循环终止。输入终止的核心问题集中在输入处理环节。

内容的提问来源于stack exchange,提问作者ege.exe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:32:29