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

Java使用for循环创建多个对象时输入缓冲区与数组越界问题如何解决

问题原因分析
  • 数组越界错误:你输出数组内容时写的是for(i=0;i<10;i++),但数组arr的长度是用户输入的n,只要n不等于10,就会出现访问数组不存在的索引的情况,直接触发ArrayIndexOutOfBoundsException。
  • Scanner输入缓冲区错位问题:sc.nextInt()只会读取输入的整数内容,不会处理用户输入整数后敲击的换行符,下一次调用sc.nextLine()时会直接读取到这个残留的空换行,导致company字段被空内容占用,后续输入全部错位;你额外添加的sc.nextLine()又多吞了一行model之后的输入内容,自然无法正确输出model对应的内容。
修复方案
  1. 输出循环的终止条件从i<10改为i<arr.length,匹配数组实际长度
  2. 每次调用sc.nextInt()之后,紧跟一次sc.nextLine()吃掉残留的换行符,移除中间多余的sc.nextLine()
  3. 补充说明:原代码中自定义类命名为Object会和Java原生的java.lang.Object根类产生命名冲突,建议修改为有明确含义的类名避免后续错误。

修复后完整代码如下:

import java.util.Scanner;
class Vehicle{
    String company;
    String model;
    int price;
    int wheels;
    int headlights;
    int a=10;
}

public class Main
{
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int i;
        System.out.println("Enter the number of objects you want to create:");
        int n;
        n=sc.nextInt();
        // 读取nextInt残留的换行符
        sc.nextLine();
        System.out.println("Enter the input for each object  ");
        
        Vehicle arr[] = new Vehicle[n];

        for (i=0; i<n; i++){
            System.out.println("Enter the details for the new vehicle");
            arr[i] = new Vehicle();
            arr[i].company=sc.nextLine();
            arr[i].model=sc.nextLine();
            arr[i].price= sc.nextInt();
            arr[i].wheels=sc.nextInt();
            arr[i].headlights=sc.nextInt();
            // 读取本轮整数输入后残留的换行符
            sc.nextLine();
        }

        System.out.println();

        // 循环条件匹配数组实际长度
        for(i=0;i<arr.length;i++){
            System.out.println(arr[i].company);
            System.out.println(arr[i].model);
            System.out.println(arr[i].price);
            System.out.println(arr[i].wheels);
            System.out.println(arr[i].headlights);
        }
        sc.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 14:27:02