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

Java字符串队列开发:输入过滤及整数提取功能实现问题求助

实现代码
import java.util.Queue;
import java.util.Scanner;
import java.util.Iterator;
import java.util.LinkedList;

public class Main {
    public static void main (String args[]){
        Scanner scan = new Scanner(System.in);
        System.out.println("This is a Queue program. Please enter how many integer/s will be inputted.");
        int count = scan.nextInt();
        scan.nextLine();
        System.out.println("Enter the valid interger/s:");
        String[] inputList = new String[count];

        for (int i = 0; i < count; i++){
            inputList[i] = scan.nextLine();
        }
        Queue<String> numQueue = new LinkedList<>();

        // 遍历处理每一条输入
        for (String input : inputList){
            // 第一步:校验是否包含非法特殊字符
            if (!input.matches("^[a-zA-Z0-9]+$")) {
                System.err.println("错误:输入包含禁止的特殊字符(含空格)");
                System.exit(1);
            }
            // 第二步:提取输入中的所有数字
            String numStr = input.replaceAll("[^\\d]", "");
            // 过滤无数字的输入项
            if (!numStr.isEmpty()) {
                numQueue.add(numStr);
            }
        }

        // 输出存储数字字符串的队列
        System.out.println("提取到的数字队列:" + numQueue);

        // 转为整数数组逻辑
        int[] numArray = new int[numQueue.size()];
        int index = 0;
        Iterator<String> iterator = numQueue.iterator();
        while(iterator.hasNext()){
            numArray[index] = Integer.parseInt(iterator.next());
            index++;
        }
        // 输出整数数组
        System.out.print("最终整数数组:");
        for (int num : numArray) {
            System.out.print(num + " ");
        }
    }
}
核心逻辑说明
  • 非法字符校验:通过正则^[a-zA-Z0-9]+$匹配全量输入,只要出现字母、数字以外的字符,直接返回错误终止程序
  • 数字提取:调用replaceAll("[^\\d]", "")移除所有字母字符,仅保留数字部分
  • 空值过滤:排除仅输入字母、提取后无有效数字的项

内容的提问来源于stack exchange,提问作者VenGoesFarming

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:03