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

Java中如何限制控制台输入行数?实现最多8行输入并支持提前终止

Fixing Input Handling and Loop Logic for Your Test Case Processor

Hey there! Let's fix up your code to meet the input requirements and get the correct output as shown. I'll break down the issues and walk you through the corrected version step by step.

Key Issues in the Original Code

  • Variables e, m, i, j aren't properly declared or initialized within the method.
  • No limit on the number of input lines (needs to cap at 8).
  • Using nextInt() leaves newline characters in the input buffer, which breaks subsequent hasNextLine() checks.
  • No logic to handle early termination when the user enters an empty line.
  • The inner loop condition is incorrect (it runs while i !=0 || j !=0, which doesn't align with the required step-counting logic).

Corrected Code

import java.util.Scanner;

public class TestCaseProcessor {
    public static void doSomething() {
        Scanner input = new Scanner(System.in);
        int lineCount = 0;
        final int MAX_LINES = 8;

        while (lineCount < MAX_LINES && input.hasNextLine()) {
            String line = input.nextLine().trim();
            
            // Early termination: stop if user enters an empty line
            if (line.isEmpty()) {
                break;
            }

            // Split line into two integers
            String[] parts = line.split("\\s+");
            if (parts.length != 2) {
                System.out.println("Invalid input: please enter two numbers per line.");
                continue;
            }

            try {
                int i = Integer.parseInt(parts[0]);
                int j = Integer.parseInt(parts[1]);
                
                int num = 0;
                int e = i;
                int m = j;

                // Count steps until both e and m reset to 0
                while (!(e == 0 && m == 0)) {
                    num++;
                    e = (e + 1) % 100;
                    m = (m + 1) % 400;
                }

                // Format output as requested
                System.out.printf("C%d: %d%n", lineCount + 1, num);
                lineCount++;
            } catch (NumberFormatException ex) {
                System.out.println("Invalid input: please enter valid integers.");
            }
        }

        input.close();
    }

    public static void main(String[] args) {
        doSomething();
    }
}

What's Changed and Why

  • Line Count Limit: Added lineCount to track valid test cases, stopping automatically once it hits 8.
  • Early Termination: Trims input lines and breaks the loop if an empty line is detected (matches your "press enter to stop early" requirement).
  • Safe Input Parsing: Reads entire lines first with nextLine() to avoid buffer issues, then splits and parses integers. Includes error handling for invalid inputs.
  • Proper Inner Loop: Initializes e and m with the input values, then increments them each step until both reach 0. This aligns perfectly with your example output.
  • Formatted Output: Uses printf to generate the C1: X style output you specified.

Testing with Your Example Input

If you run the code and enter:

0 0
100 300
99 399
0 200
(press enter for empty line to stop early)

You'll get the exact expected output:

C1: 0
C2: 100
C3: 1
C4: 200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:27:49