Java使用Scanner读取命令行多行输入仅输出最后一行如何解决
问题原因及修复方案
1. 输入处理环节的潜在问题
你当前使用split(" ")分割每行内容,当输入行存在首尾空格、多空格间隔、制表符时,会生成空字符串元素,可能触发ArrayIndexOutOfBoundsException导致程序提前终止,仅能输出最后一行之前无异常的结果。同时部分运行环境下控制台输出存在缓冲区积压,也会导致前序输出未及时显示。
修复代码如下:
public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNextLine()) { String line = input.nextLine().trim(); // 跳过空行 if (line.isEmpty()) { continue; } // 用\\s+匹配任意长度的空白字符 String[] lines = line.split("\\s+"); if (lines.length >= 2) { System.out.println(fct(lines[0], lines[1])); // 强制刷新输出缓冲区,保证结果即时打印 System.out.flush(); } } input.close(); }
2. fct大数减法逻辑缺陷
你的减法逻辑默认被减数大于等于减数,仅在两个数字长度不同时做了交换,未处理长度相同但被减数小于减数的场景(比如第一行输入的10和12),会导致计算结果错误,极端场景下也可能触发异常。
需要先新增大小判断逻辑,保证计算时被减数始终大于等于减数:
// 新增方法:判断a是否大于等于b private static boolean isBiggerOrEqual(String a, String b) { if (a.length() != b.length()) { return a.length() > b.length(); } for (int i = 0; i < a.length(); i++) { if (a.charAt(i) != b.charAt(i)) { return a.charAt(i) > b.charAt(i); } } return true; } // 修改后的fct方法 public static String fct(String stringA, String stringB) { // 保证被减数大于等于减数,不满足就交换参数 if (!isBiggerOrEqual(stringA, stringB)) { return fct(stringB, stringA); } int [] a = new int[stringA.length()]; int [] b = new int[stringB.length()]; for(int i=0; i< stringA.length(); i++) { a[i] = stringA.charAt(i) - '0'; } for(int i=0; i< stringB.length(); i++) { b[i] = stringB.charAt(i) - '0'; } Stack<Integer> s = new Stack<>(); int carry = 0; int b_ind = b.length -1; for(int i=a.length-1; i>=0; i--) { if(b_ind >= 0) { int diff = a[i] - b[b_ind] - carry; if(diff < 0) { carry = 1; diff = 10 + diff; } else { carry = 0; } s.push(diff); } else { if(carry==0) { s.push(a[i]); } else { s.push(a[i]-carry); carry = 0; } } b_ind -= 1; } StringBuilder all = new StringBuilder(); while(!s.empty()) { all.append(s.pop()); } return all.toString().replaceFirst("^0+(?!$)", "").trim(); }
修复后即可得到预期的三行输出:
2 71293781685339 12345677654320
内容的提问来源于stack exchange,提问作者user6346482
相关产品推荐
相关产品推荐

