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

如何使用Java实现分两行输入两个不同的数字

实现代码

import java.util.Scanner;

public class InputTwoNumbers {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 读取第一行数字
        String firstNumStr = scan.nextLine().trim();
        // 读取第二行数字
        String secondNumStr = scan.nextLine().trim();
        
        // 如果需要转换为整数类型使用,可添加以下逻辑
        int firstNum = Integer.parseInt(firstNumStr);
        int secondNum = Integer.parseInt(secondNumStr);
        
        // 验证读取结果,可根据实际需求删除
        System.out.println("读取到的第一个数字:" + firstNum);
        System.out.println("读取到的第二个数字:" + secondNum);
        
        scan.close();
    }
}

说明

  • 你之前的代码只调用了一次nextLine(),只能读取第一行输入,因此无法获取第二行的数字,新增一次nextLine()调用即可读取第二行内容
  • 如果输入可能存在非数字字符,建议给Integer.parseInt()逻辑添加try-catch块捕获NumberFormatException,做异常兼容处理
  • 不需要转数字的话,直接使用firstNumStr和secondNumStr两个字符串变量即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:45:03