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

Java如何从方法中返回数组并正确调用获取返回值

问题原因
  • 返回值类型不匹配:方法签名声明返回int[],但你当前尝试返回的booking是Booking[]类型,类型不一致导致编译报错。
  • 变量作用域错误:Booking[] booking定义在if(dis==1)代码块内部,代码块外部无法访问该变量,在if块外调用return会提示变量未定义。
  • 未提取目标字段:你需要的是客户ID数组,需遍历已赋值的Booking对象,单独提取customerID属性组装新的int数组。
冗余代码优化提示
  • 处理tokens[3]的for循环完全冗余:你循环了tokens[3].length()次做重复赋值,且split方法返回的元素不可能为null,最多是空字符串,原有判断逻辑无效。
  • 固定长度为20的Booking数组如果遇到文件行数超过20会触发数组越界,建议改用ArrayList动态存储。
修改后的完整代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public static int[] booking(int dis) { 
    // 定义存储客户ID的动态集合,避免固定长度溢出问题
    List<Integer> customerIdList = new ArrayList<>();
    Scanner date = new Scanner(System.in);
    String inputDate;
    if(dis==1) {
        System.out.println("Input the date for the booking");
        inputDate = date.next();
        String str;
        String[] tokens = null;
        int num;
        // 改用ArrayList存Booking对象,支持动态扩容
        List<Booking> bookingList = new ArrayList<>();
        File f = new File("bookings-"+inputDate+".txt");
        try {
            Scanner file = new Scanner(f); 
            while(file.hasNext()) {
                str=file.nextLine();
                tokens=str.split(",");              
                Booking booking = new Booking();
                booking.setBookingId(Integer.parseInt(tokens[0]));
                booking.setCustomerID(Integer.parseInt(tokens[1]));
                booking.setBookingDate(tokens[2]);
                // 优化原有冗余循环逻辑
                if(tokens[3].trim().isEmpty()) {
                    booking.setTotalPrice(0f);
                } else {
                    booking.setTotalPrice(Float.parseFloat(tokens[3]));
                }
                num=tokens.length-4;
                int[] intArray = new int[num];
                for(int i = 0; i < num; i++) {
                    intArray[i] = Integer.parseInt(tokens[4+i]);
                }
                booking.setServiceCodes(intArray);
                bookingList.add(booking);
                // 同时存入客户ID集合
                customerIdList.add(booking.getCustomerID());
            }
            // 原有打印逻辑可保留
            for(Booking b : bookingList) {
                System.out.println(b.getCustomerID());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    // List转int数组返回
    return customerIdList.stream().mapToInt(Integer::intValue).toArray();
}

如果你的项目不支持Java8及以上的stream写法,可替换转数组的逻辑为:

int[] res = new int[customerIdList.size()];
for(int i=0; i<res.length; i++){
    res[i] = customerIdList.get(i);
}
return res;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:48:03