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

Java中nextLine()读取shipname数组从索引1开始而非0的问题排查

Hey there! Let's tackle the issues in your code and get that Green Dart Shipping lookup system working properly.

Core Issues in Your Current Code

Let's start by addressing the two problems you've noticed:

  • Empty shipname[0]: When you use reader.nextInt(), it only captures the integer value and leaves the newline character (from pressing Enter) in the input buffer. The first nextLine() call picks up this leftover newline instead of the actual shipment name, hence the empty first index.
  • Array Out-of-Bounds Risk: Your shipment name loop uses j < m+1, but your shipname array is initialized with size m. When j reaches m, you'll try to access shipname[m]—an index that doesn't exist—triggering an ArrayIndexOutOfBoundsException.

Fixed Code with Full Business Requirement Implementation

Here's the corrected code that fixes both issues and adds the cargo lookup functionality your business needs:

import java.util.*;

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

        // Read cargo IDs
        System.out.println("Enter the number of cargo");
        int n = reader.nextInt();
        int[] cargoid = new int[n];
        System.out.println("Enter the cargo id");
        for (int i = 0; i < n; i++) {
            cargoid[i] = reader.nextInt();
        }

        // Fix: Consume the leftover newline after reading cargo count/IDs
        reader.nextLine();

        // Read shipment names correctly
        System.out.println("Enter the number of shipment");
        int m = reader.nextInt();
        // Fix: Consume newline again after reading shipment count
        reader.nextLine();
        String[] shipname = new String[m];
        System.out.println("Enter the shipment name");
        for (int j = 0; j < m; j++) {
            shipname[j] = reader.nextLine();
        }

        // Implement cargo lookup functionality
        System.out.println("Enter the cargo ID to look up:");
        int lookupId = reader.nextInt();
        boolean cargoFound = false;
        
        for (int k = 0; k < n; k++) {
            if (cargoid[k] == lookupId) {
                // Check if there's a corresponding shipment name
                if (k < m && shipname[k] != null && !shipname[k].isEmpty()) {
                    System.out.println(shipname[k]);
                } else {
                    System.out.println("Yet to be shipped");
                }
                cargoFound = true;
                break;
            }
        }
        
        // If cargo ID doesn't exist at all
        if (!cargoFound) {
            System.out.println("Yet to be shipped");
        }

        reader.close();
    }
}

Key Fixes & Explanations

  • Leftover Newline Handling: After every nextInt() call that's followed by nextLine(), we add reader.nextLine() to consume the unused newline character. This ensures the subsequent nextLine() reads the actual user input instead of an empty string.
  • Corrected Loop Bound: Changed the shipment name loop to j < m to match the array's size, eliminating the out-of-bounds error risk.
  • Cargo Lookup Logic: Added the core business functionality:
    1. Prompt the user for a cargo ID to look up
    2. Search the cargoid array for the ID
    3. If found, check if there's a corresponding shipment name (and it's not empty)
    4. Return the shipment name if available, otherwise return "Yet to be shipped"
    5. If the cargo ID isn't found at all, also return "Yet to be shipped"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:22:13