如何用for循环提取对象特定属性存入数组?以用户PIN为例
没问题,我来帮你搞定这个需求!你已经把Customers类的getPin()写好了,这可是关键一步——接下来只需要把创建好的客户对象存起来,再用for循环挨个提取PIN就行,看我给你一步步演示:
完整可运行代码示例
public class Customers { private String first; private String last; private int pin; public Customers(String fn, String ln, int p) { this.first = fn; this.last = ln; this.pin = p; System.out.println(first + " " + last+ " Pin: " +pin); } public int getPin() { return pin; } } public class MainMethod{ public static void main(String [] args) { // 1. 先创建多个Customers实例,存到数组里(也可以用ArrayList动态添加) Customers[] customers = { new Customers("John", "Doe", 1234), new Customers("Jane", "Smith", 5678), new Customers("Bob", "Brown", 9012) }; // 2. 初始化存储PIN的数组,长度和客户数组保持一致 int[] customerPins = new int[customers.length]; // 3. 用普通for循环遍历,提取每个客户的PIN for (int i = 0; i < customers.length; i++) { // 调用getPin()获取私有pin属性,存入PIN数组 customerPins[i] = customers[i].getPin(); } // 验证提取结果 System.out.println("\n提取到的PIN数组内容:"); for (int pin : customerPins) { System.out.println(pin); } } }
关键逻辑解释
- 为什么用
getPin()? 因为你把pin定义成了私有属性(private int pin),外部类(比如MainMethod)不能直接访问,必须通过你写的公共getter方法getPin()来获取,这符合Java的封装原则,你的代码已经正确实现了这一点~ - 两种for循环写法:上面用的是普通for循环,如果你更喜欢简洁的增强for循环,也可以这么写(需要额外一个索引变量来定位PIN数组的位置):
int index = 0; for (Customers customer : customers) { customerPins[index++] = customer.getPin(); }
扩展小提示
如果你的客户数量不确定,建议用ArrayList<Customers>来存储客户对象,这样可以动态添加,然后再转成PIN数组:
import java.util.ArrayList; public class MainMethod{ public static void main(String [] args) { ArrayList<Customers> customerList = new ArrayList<>(); customerList.add(new Customers("John", "Doe", 1234)); customerList.add(new Customers("Jane", "Smith", 5678)); int[] customerPins = new int[customerList.size()]; for (int i = 0; i < customerList.size(); i++) { customerPins[i] = customerList.get(i).getPin(); } } }
内容的提问来源于stack exchange,提问作者Allen Williams
相关产品推荐
相关产品推荐

