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

Java中如何从字符串提取整数并存储到独立变量中?

解决输入"new 10 32"提取宽高的问题

原代码存在的问题

  • 提取命令词"new"的逻辑错误:循环取前5个字符会包含多余空格,且word.trim()未重新赋值(String是不可变对象,trim()返回新字符串),导致word.equals("new")判断永远不成立。
  • 数字提取逻辑有漏洞:遇到第一个空格后check设为true,后续所有字符(包括空格)都会被加入number2,导致number2可能包含非数字字符,无法正确转换为整数。
  • 缺少字符串转整数的核心步骤,未将提取的字符串转为int类型赋值给width和height。

修正后的代码(基于原思路改进)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String input = scanner.nextLine();
        String word = "";
        int spaceIndex = input.indexOf(' ');
        
        // 正确提取开头的命令词
        if (spaceIndex != -1) {
            word = input.substring(0, spaceIndex).trim();
        } else {
            word = input.trim();
        }

        if (word.equals("new")) {
            // 截取命令词后的数字部分,按空格分割
            String numsPart = input.substring(spaceIndex + 1).trim();
            String[] nums = numsPart.split("\\s+"); // 兼容多个空格的情况
            
            if (nums.length >= 2) {
                try {
                    int width = Integer.parseInt(nums[0]);
                    int height = Integer.parseInt(nums[1]);
                    System.out.println("width: " + width + ", height: " + height);
                } catch (NumberFormatException e) {
                    System.out.println("输入的数字格式不正确");
                }
            } else {
                System.out.println("缺少足够的数字参数");
            }
        } else {
            System.out.println("命令不是new");
        }

        scanner.close();
    }
}

更简洁的实现方式(利用Scanner内置方法)

Scanner默认按空格分割输入,直接用next()读取命令词,nextInt()读取整数,无需手动处理字符串:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        if (scanner.hasNext("new")) {
            scanner.next(); // 跳过命令词"new"
            // 检查是否有两个整数输入
            if (scanner.hasNextInt() && scanner.hasNextInt()) {
                int width = scanner.nextInt();
                int height = scanner.nextInt();
                System.out.println("width: " + width + ", height: " + height);
            } else {
                System.out.println("输入的数字格式不正确");
            }
        } else {
            System.out.println("命令不是new");
        }

        scanner.close();
    }
}

这种方式更简洁可靠,自动处理空格分隔,直接读取int类型,同时包含了输入格式的异常判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:50:34