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

如何在Java控制台读取[[1,2,3,4],5]格式输入为数组A与变量B?

Parsing Formatted Input Like "[[1,2,3,4],5]" in Java

Hey there! Let's tweak your input handling to work with that bracket-and-comma structured input instead of the space-separated format your current code uses. Here's a straightforward approach and adjusted code to get this done:

Step-by-Step Breakdown

  • Grab the full input line: Since your input is a single cohesive string, we'll read the entire line first instead of relying on nextInt() which splits on whitespace.
  • Clean and split the input: Strip off the outer brackets, then split the remaining content into two distinct parts: the array substring and the value for B.
  • Parse the array: Take the array substring, remove its inner brackets, split by commas, and convert each element to an int to build array A.
  • Parse variable B: Convert the second segment of the split string directly to an int.

Modified Code

import java.util.Scanner;

public class InputHandler {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        while (scanner.hasNextLine()) {
            // Read the entire input line and trim any extra whitespace
            String input = scanner.nextLine().trim();
            
            // Skip empty lines if they're present
            if (input.isEmpty()) {
                continue;
            }
            
            // Remove the outer brackets to get the core content
            String coreContent = input.substring(1, input.length() - 1);
            // Split into array part and B part using "], " as the separator
            String[] segments = coreContent.split("],");
            
            // Parse array A from the first segment
            String arrayContent = segments[0].substring(1); // Remove the leading [
            String[] arrayStrElements = arrayContent.split(",");
            int[] A = new int[arrayStrElements.length];
            for (int i = 0; i < arrayStrElements.length; i++) {
                A[i] = Integer.parseInt(arrayStrElements[i].trim());
            }
            
            // Parse variable B from the second segment
            int B = Integer.parseInt(segments[1].trim());
            
            // Call your Solutions method and output the result
            int result = Solutions(A, B);
            System.out.println(result);
        }
        scanner.close();
    }
    
    // Replace this with your actual Solutions implementation
    private static int Solutions(int[] A, int B) {
        // Example logic: sum all elements in A and add B
        int total = 0;
        for (int num : A) {
            total += num;
        }
        return total + B;
    }
}

Quick Notes

  • This code assumes your input strictly follows the [[x1,x2,...,xn],y] format (it handles minor extra spaces with trim()).
  • If you need to account for invalid inputs (like typos or wrong formatting), wrap the parsing steps in a try-catch block to catch NumberFormatException or StringIndexOutOfBoundsException and handle errors gracefully.
  • The loop will process one input line at a time, so it works for multiple entries if you're feeding them line by line.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 06:42:28